简体   繁体   中英

how to get checkbox values in javascript

i want to set more value to checkbox,how do it? this is my code: from this code only i could get upto 3 value,why? i want to get 5 value.how do it?

$results=$watch.",".$thumbnail.",".$name.",".$description.",".$val;
<input type="checkbox" name="checkbox[]" id="checkbox[]" class="addbtn"  value=<?php echo  $results;?>

javascript fn:

  function chkbox()
  { 
 $('[name^=checkbox]:checked').each(function() {

 var ckballvalue=($(this).val());  

 var latlngStrs = ckballvalue.split(",",5);
 var link = latlngStrs[0];
 var thumbnail = latlngStrs[1];
 var name = latlngStrs[2];
 var description = latlngStrs[3];
 var categ = latlngStrs[4];

 alert(link+thumbnail+name+description+categ);
   }

Assuming your markup is correct and you're using POST , then you just grab them from the $_POST variable in PHP.

$checkedValues = $_POST['checkbox'];

This will be an array of all checked values, where 'checkbox' is the name of your input group.

When a browser posts a form containing checkboxes, it only posts anything for the checkboxes that have been checked. The ones that are unchecked will not be sent at all.

Therefore, if you have five checkboxes, but only three are checked, your PHP $_POST or $_GET array will only contain entries for those three, not the other two.

This will also means that if you're using name="checkbox[]" for all your checkboxes, then your array elements will not be numbered as you expect.

Note that this is the way HTML forms work; it's got nothing to do with PHP.

If you want to force it, you could have a hidden field on the form which mirrors the checkbox state using Javascript. This way you'll be certain you'll always get the value posted to you whether it was checked or not.

Or you could just accept the way it works. You may not get the values posted to you if they aren't checked, but their absence is sufficient, as not having those field posted allows you to know that they weren't checked.

You might find it helpful to give your checkboxes explicit array element keys -- ie rather than name="checkbox[]" , use name="checkbox[3]" . This way they'll always be posted into the right slot in your $_POST array.

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM