我在数据库表中有位置名称和位置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()" />';
答案 0 :(得分:21)
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);
答案 1 :(得分:2)
这是一种变体,可以在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);
答案 2 :(得分:2)
var fav = [];
$.each($("input[name='name']:checked"), function(){
fav.push($(this).val());
});
它将为您提供逗号分隔的值
答案 3 :(得分:0)
我使用的是jQuery,您可以将复选框放在表单中,然后使用以下内容:
var formData = jQuery("#" + formId).serialize();
$.ajax({
type: "POST",
url: url,
data: formData,
success: success
});
答案 4 :(得分:0)
在某些情况下,一次处理一个选定的项目可能更有意义。
换句话说,为每个选定项目单独调用服务器,传递所选项目的值。在某些情况下,列表需要作为一个整体进行处理,但有些则不需要。
我需要处理所选人员的列表,然后将查询结果显示在该人员现有数据下方的现有页面上。我最初将整个列表传递给服务器,解析列表,然后传回所有患者的数据。然后我需要解析返回的数据并将其插入到每个适当位置的页面中。一次发送一个人的数据请求变得更容易。此处描述了用于获取所选项目的Javascript:check if checkbox is checked javascript,此处描述了相同的jQuery:How to check whether a checkbox is checked in jQuery?。
答案 5 :(得分:0)
这段代码对我来说很好,这里我用#符号
将数组转换为字符串 <input type="checkbox" value="created" name="today_check"><strong> Created </strong>
<input type="checkbox" value="modified" name="today_check"><strong> Modified </strong>
<a class="get_tody_btn">Submit</a>
<script type="text/javascript">
$('.get_tody_btn').click(function(){
var ck_string = "";
$.each($("input[name='today_check']:checked"), function(){
ck_string += "~"+$(this).val();
});
if (ck_string ){
ck_string = ck_string .substring(1);
}else{
alert('Please choose atleast one value.');
}
});
</script>