skip to Main Content

Can’t figure out why this loop won’t give me the info i’m wanting

I have a page with a few hundred inputs on it , i want to get the the input "name" value for each input that is checked

<input type="checkbox" name="TAXI_SQUAD0001" checked="checked">
<input type="checkbox" name="TAXI_SQUAD0021" checked="checked">
<input type="checkbox" name="TAXI_SQUAD0011">   


$.ajax({
    url: urlHPM,
    xhrFields: {
        withCredentials: true
    },
    cache: false,
    type: "GET",
    success: function (data) {
        checkedInputs = $(data).find('input[checked="checked"]'); 
        for (var i = 0; i < checkedInputs.length; i++) {
            console.log(checkedInputs.attr('name')[i]); // loops character of first name of first input over and over
            console.log(checkedInputs[i].attr('name')); // error attr not a function
            // i want to log input names TAXI_SQUAD0001 and TAXISQUAD0021
        }

    },
    error: function (xhr) {
    }
});

2

Answers


  1. You are accessing the DOM when you do checkedInputs[i]. It is not the jQuery wrapped code. You can do checkedInputs.eq(i).attr('name') or just checkedInputs[i].name

    Your code also does not need the for loop. You can just use each.

    checkedInputs.each(function () {
      var cb = $(this);
      console.log(cb.attr('name'));
    });
    
    Login or Signup to reply.
  2. You can loop all checked checkboxes in the ajax success response using the .each() jQuery function.

    $.ajax({
        url: urlHPM,
        xhrFields: {
            withCredentials: true
        },
        cache: false,
        type: "GET",
        success: function (data) {
            checkedInputs = $(data).find('input[checked="checked"]');
            $(checkedInputs).each(function(){
                //Log the input name attribute
                console.log($(this).attr('name'));
            });
        },
        error: function (xhr) {
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search