我在数据库表中有位置名称和位置ID。使用foreach循环,我在PHP的复选框中打印值。我有一个触发JavaScript的提交按钮。我希望用户在javascript变量中选择所有用逗号分隔的复选框值。我怎样才能做到这一点?
<!-- Javascript --> <script> function getLoc(){ var all_location_id = document.getElementByName("location[]").value; var str = <!-- Here I want the selected checkbox values, eg: 1, 4, 6 --> } <script> foreach($cityrows as $cityrow){ echo '<input type="checkbox" name="location[]" value="'.$cityrow['location_id'].'" />'.$cityrow['location']; echo '<br>'; } echo '<input name="searchDonor" type="button" class="button" value="Search Donor" onclick="getLoc()" />';
var checkboxes = document.getElementsByName('location[]'); var vals = ""; for (var i=0, n=checkboxes.length;i<n;i++) { if (checkboxes[i].checked) { vals += ","+checkboxes[i].value; } } if (vals) vals = vals.substring(1);