6

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()" />';
Alien2828
  • 109
  • 1
  • 2
  • 10

6 Answers6

31
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);
Community
  • 1
  • 1
user7789076
  • 798
  • 2
  • 12
  • 25
6

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);
ilpaijin
  • 3,645
  • 2
  • 23
  • 26
  • Please add some explanation to your post. – DontVoteMeDown Nov 19 '13 at 10:57
  • Ok, did it. Sorry I'm new here. Is it mandatory to add an explanation only if the answer isn't marked as "best answer"? – ilpaijin Nov 19 '13 at 11:02
  • I wouldn't say "mandatory" but is a good pratice in order to provide a good quality question. This site cares about it's quality. I commented to you because your post was voted to be close, but it disagree with closing. Please read [this](http://meta.stackexchange.com/q/7656/223068). – DontVoteMeDown Nov 19 '13 at 11:08
  • 1
    Ah Ok, I've just wonder why you just commented me and not the "best answer", maybe there was a rule which I didn't still know. Anyway, many thanks. I'll pay attention to provide more quality in my answer. – ilpaijin Nov 19 '13 at 11:15
  • You're right. The accepted answer doesn't get the perfect pattern too. But that happened because I have been noticed about your question because somebody *flagged* it as "Low Quality". This make your question to be listed on a section inside the "[review](http://stackoverflow.com/review/)" section(link aside your badges on header), so I only see your post, not the entire list of answers. Feel free to flag it, or comment it if you think that is something wrong. – DontVoteMeDown Nov 19 '13 at 11:20
4
var fav = [];
$.each($("input[name='name']:checked"), function(){            
    fav.push($(this).val());
});

It will give you the value separeted by commas

VincenzoC
  • 30,117
  • 12
  • 90
  • 112
Manmeet Khurana
  • 367
  • 2
  • 13
0

I you are using jQuery you can put the checkboxes in a form and then use something like this:

var formData = jQuery("#" + formId).serialize();

$.ajax({
      type: "POST",
      url: url,
      data: formData,
      success: success
}); 
John
  • 3,458
  • 4
  • 33
  • 54
0

In some cases it might make more sense to process each selected item one at a time.

In other words, make a separate server call for each selected item passing the value of the selected item. In some cases the list will need to be processed as a whole, but in some not.

I needed to process a list of selected people and then have the results of the query show up on an existing page beneath the existing data for that person. I initially though of passing the whole list to the server, parsing the list, then passing back the data for all of the patients. I would have then needed to parse the returning data and insert it into the page in each of the appropriate places. Sending the request for the data one person at a time turned out to be much easier. Javascript for getting the selected items is described here: check if checkbox is checked javascript and jQuery for the same is described here: How to check whether a checkbox is checked in jQuery?.

Community
  • 1
  • 1
John
  • 3,458
  • 4
  • 33
  • 54
0

This code work fine for me, Here i contvert array to string with ~ sign

    <input type="checkbox" value="created" name="today_check"><strong>&nbsp;Created&nbsp;&nbsp;</strong>
    <input type="checkbox" value="modified" name="today_check"><strong>&nbsp;Modified&nbsp;</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>
Sandeep Sherpur
  • 2,418
  • 25
  • 27