Ali*_*828 4 javascript php forms ajax checkbox
我在数据库表中有位置名称和位置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()" />';
Run Code Online (Sandbox Code Playgroud)
use*_*076 23
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);
Run Code Online (Sandbox Code Playgroud)
all_location_id这是一种在不使用“if”语句的情况下获取所有选中复选框的变体
var all_location_id = document.querySelectorAll('input[name="location[]"]:checked');
var aIds = [];
for(var x = 0, l = all_location_id.length; x < l; x++)
{
aIds.push(all_location_id[x].value);
}
var str = aIds.join(', ');
console.log(str);
Run Code Online (Sandbox Code Playgroud)