Get all "marked" checkboxes in a dynamically generated list from jQuery

Asked

Viewed 5,868 times

2

I have a modal in which it contains a list that is generated dynamically by jQuery via a callback of AJAX.

The question is that I need to get the id’s of all the "checkbox’s" that were selected in it. I’m almost sure I’ll need the method .on(), but I just don’t know how I can do the same.

Below is my list which is generated dynamically:

<ul id="list-of-passenger-service-item" class="list-cadastro skin skin-flat">
   <li>
       <input type="checkbox" id="25">
       <label>Claudia Fernadez - Filho(a) - 09/06/2000</label>
   </li>
</ul>

I have tried something like this, but unfortunately I did not succeed, because it "jumps" the .on():

$(document).on('change', '[type=checkbox]', function() {
    $(this).each(function(){
        console.log('obter os id\'s e armazenar em um array');
    });
}); 

EDITION

I will try to summarize the flow for better understanding of all.

I have a button that aims to open a modal:

//Abre o Modal e realiza o append (Exemplo para ilustração do meu caso)
$('#open-modal-item').click(function (event){
    event.preventDefault();
    $('#modalItem').modal('show');

    //Chamada AJAX omitida

    $('#list-of-passenger-service-item').append("<li> <input type=\"checkbox\" id=\""+value.id+"\"> <label>" + value.firstName + " " + value.lastName + " - Cônjuge - " + date.toLocaleDateString()  + '</label> </li>');

});

Soon, in my modal I have a button that aims to carry out data confirmation:

$('#service-item-btn-confirm').click(function (event){
   event.preventDefault();

   //Varias linhas foram omitidas para facilitar o entedimento

   //Chamo o metodo que tem como objetivo construir um objeto JSON para posteriormente passar para o back-end
   constructServiceItemObj();
})

Finally within the method constructServiceItemObj(); i need to get all checkbox’s components that were selected by the user:

function constructServiceItemObj(){
    $("input:checkbox[name=type]:checked").each(function(i, el){
        var id = $(this).find(':input');
    });

});

Unfortunately the same does not work! Precisely for the reason (I believe) that the elements of my checkbox list are generated dynamically, so I may need a .on() in my $.each().

2 answers

7


You won’t need to use the on() in this case, because what you want is to pick up the Ids at a certain time, right? As in the click of a button?

So, considering that you have a button that when clicked will catch these Ids (can be another event, the main one here is the central part of the code below), you can use the selector :checked to pick up checkboxes that are marked.

$("#botaoEnviar").click(function(){
  $("input:checked").each(function(){
    console.log($(this).attr("id"));
  });
});

Take the test and see if it fits.

  • Hi Joel I think I need the .on(), because every time I enter my "modal" $('#open-modal-item').click(function (event){}); i perform an ajax call, in which it aims to return values that will be "appendados" dynamically. I soon believe the use of .on() becomes necessary. I tested the example you gave me, but unfortunately the same did not work.

  • 1

    I made a small example, see if it is more or less similar to what you need: https://jsfiddle.net/xsqb7a6s/. I didn’t use the .on.

  • Joel finally worked. But I had to make a change. In my component of <ul> I had two classes css so-called: .skin .skin-flat, soon all the cases cited here worked! The problem apparently was those two classes that were preventing the functioning, I just don’t know for sure what the reason.

3

To select the checkbox you need a CSS selector that includes what you want.

input[type="checkbox"] does this, or even the pseudo-selector of jQuery ":checkbox". But you should also use a common DOM class or element to make sure you only get the inputs you want.

To select:

var inputs = $('.lista-cadastros :checkbox');

eventually using the :checked to filter those that are not marked

to know the Ids:

var ids = inputs.map(function(){
    return this.id;
});

if you need a native array and not a jQuery object you can call the .get(); in the end:

var ids = inputs.map(function(){
    return this.id;
}).get();

The second part where you write "I need to get the id’s of all checkboxes that were selected in the same" may need the .on(). The question is not clear when you need to run that code. In case the element that triggers this code has been dynamically added then yes need the .on() with delegation. In the simplest case you can use:

$(document).on('click', 'seletor-para-o-elemento', function(){
  • Hello Sergio! Edite4i the question to make clear my need. But probably I need the .on().

  • 1

    @Joãomanolo and these inputs are within the same <ul>?

  • 1

    @Would Jonathan be something like that? -> http://jsfiddle.net/9Lcv99xe/

  • unfortunately it didn’t work! I can’t understand the reason. When I "debunk" the document . js it simply skips the function!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.