Home > Software engineering >  Getting an error when i loop through to get input name value
Getting an error when i loop through to get input name value

Time:08-16

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) {
    }
});

CodePudding user response:

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'));
});

CodePudding user response:

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) {
    }
});
  • Related