简体   繁体   中英

Get value from dynamically created checkboxes if checked

I made few checkboxes along with a button which on submit calls a function where I want to get all the values of checkboxes which have been checked.

Code for creating those checkboxes is:

for (var loop=0; loop < count; loop++)
{

  var chap  =   document.createElement("input");
  chap.type =   "checkbox";
  chap.value    =   nearby[loop];
  chap.id   =   nearby[loop];

  document.getElementById("mapdisplay").appendChild(chap);
  var nearo = nearby[loop];
  var s     =   document.getElementById("mapdisplay");
  var text  =   document.createTextNode(nearby[loop]);
  s.appendChild(text);
  var br        =   document.createElement('br');
  s.appendChild(br);
}

Now I want to retrieve the values which are checked. I am trying this (but to no available)

function fsearch()
{
    var p       =   x;
    var narr    =   new Array();
    narr=nearby;//a global arr
    var checked_vals = new Array(); 
    $('#mapdisplay input:checkbox:checked').foreach()

             {
              checked_vals.push(this.value);

             }

Please suggest something to retrieve the checked values id of generated values are in array form. I can not use $("#nearby[0]").val() .

var checkedCheckBoxesValueArray = $('#mapdisplay input:checkbox:checked').map(
  function(){
    return this.value;
}).get();

Correct syntax would be:

$('#mapdisplay input:checkbox:checked').each(function(index) {
    checked_vals.push($(this).val());
});

Live test case: http://jsfiddle.net/e6Sr3/

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