简体   繁体   中英

Get id values from child inputs and push it to an array in Javascript on change

I am trying to get the values into an array [111, 123, 678, and so on....] basically if click parent check the values or children inputs and an output as array[], same way if checkbox is selected on its own: I am getting a good understanding of JS but still struggling with it. I have a jsfiddle http://jsfiddle.net/4ofugqvo/ and this is how the js looks like:

$(document).ready(function(){
    $('#sidebar').append(dropdown_theatre(events.level_0));

    function checkboxGroup() {
      $('#sidebarNav input[type="checkbox"]').on('change', function(){

              var checkboxes = $(this).parent().next('ul').find('input[type="checkbox"]');

              console.log(checkboxes);
        //[10101, 191919, 19191, 119191]

        if ($(this)[0].checked == true) {
          checkboxes.each(function(){
              $(this).prop('checked', true).attr('checked', 'checked');
          });
        } else {
          checkboxes.each(function(){
              $(this).prop('checked', false).removeAttr('checked');
              //console.log(this);
          });
        };

      });

    } checkboxGroup();

I forked the fiddle. http://jsfiddle.net/0g1hk7mt/

I am not quite sure it's what you're after. The array of values is available at the alert in the on change event.

var arr = [];  
function checkboxGroup() {

    $('#sidebarNav input[type="checkbox"]').on('change', function(){
      arr = [];      
      var checkboxes = $(this).parent().next('ul').find('input[type="checkbox"]');

        //console.log(checkboxes);
      //[10101, 191919, 19191, 119191]

      if ($(this)[0].checked == true) {
        checkboxes.each(function(){
            arr.push($(this).attr("id"));
            $(this).prop('checked', true).attr('checked', 'checked');
        });
      } else {
        checkboxes.each(function(){
            $(this).prop('checked', false).removeAttr('checked');
            //console.log(this);
        });
      };
     alert(arr);
    });

  } 
checkboxGroup()

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