在javascript和PHP中的字符串中获取多个选中的复选框值 [英] Getting multiple selected checkbox values in a string in javascript and PHP

查看:55
本文介绍了在javascript和PHP中的字符串中获取多个选中的复选框值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库表中有位置名称和位置ID。使用foreach循环我在PHP中的复选框中打印值。我有一个触发javascript的提交按钮。我希望用户在javascript变量中选择以逗号分隔的所有复选框值。我该怎么做?

I have location name and location Id in database table. Using foreach loop i'm printing the values in checkbox in PHP. I have a submit button which triggers a javascript. I want the user selected all checkbox values separated by comma, in a javascript variable. How can I do this?

    <!-- 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);

这篇关于在javascript和PHP中的字符串中获取多个选中的复选框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆