Alien2828 Alien2828 - 1 year ago 68
PHP Question

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 -->
function getLoc(){
var all_location_id = document.getElementByName("location[]").value;
var str = <!-- Here I want the selected checkbox values, eg: 1, 4, 6 -->


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()" />';

Answer Source
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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download