Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting multiple selected checkbox values in a string in javascript and PHP

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()" />';
like image 817
Alien2828 Avatar asked Nov 19 '13 10:11

Alien2828


2 Answers

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);
like image 102
user7789076 Avatar answered Oct 20 '22 01:10

user7789076


This is a variation to get all checked checkboxes in all_location_id without using an "if" statement

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);
like image 27
ilpaijin Avatar answered Oct 20 '22 01:10

ilpaijin