How to do an action after three dynamic elements are filled with jQuery/javascript?

Asked

Viewed 638 times

7

I have three select that are created after the user clicks on a button, ie are dynamic:

<select id="cbExercicio"><option value="0"></option></select>
<select id="cbEquipe"><option value="0"></option></select>
<select id="cbResponsavel"><option value="0"></option></select>

I’m doing so for when modify only one of them:

$(document).on('change', '#cbExercio', function(){
      // Ação
})

But I want a fucnction that is called as soon as the user fills all three and they are different from zero (which is the first blank option with value 0). How to do or how best to do??

  • When do you need to check this?

  • I updated my bfavaretto

2 answers

8


You can check the event change of the three selects, starting with a check of the value of each one of them.

So for example:

$(document).on('change', '#cbExercicio, #cbEquipe, #cbResponsavel', function(){
    if(+$('#cbExercicio').val() != 0 && +$('#cbEquipe').val() != 0 && +$('#cbResponsavel').val() != 0) {
       // Ação
    } else {
       // Ao menos um dos selects está com valor 0
    }
});

Demo no jsfiddle

  • 4

    +1 for solving the problem elegantly. For those who did not understand, the operator + before the values is a form of implicit conversion of the value selected to a number.

  • @bfavaretto $(document).on('change', 'select', function(){}); wouldn’t it be better? If an extra select appears you don’t need to be linking the event to the element by its id, pegged by its type.

  • @Philippegioseffi What if there are other selects on the page? In real life I would use a class. Here I used Ids to fit the original markup, but as I say in the reply is just an example.

  • 1

    @bfavaretto then maybe the hundred percent correct was $(document).on('change', 'select.novosSelects', function(){}); and hence these selects were created with this class.

5

It is possible to solve the problem in a more "generic" way, that is, by creating a kind of camp group using CSS classes.

A possible HTML would look like this:

<select class="meu_grupo" id="cbExercicio"><option value="0"></option><option value="1">1</option></select>
<select class="meu_grupo" id="cbEquipe"><option value="0"></option><option value="1">1</option></select>
<select class="meu_grupo" id="cbResponsavel"><option value="0"></option><option value="1">1</option></select>

So the code goes like this:

$(function() {
    $('.meu_grupo').change(function() {

        //itera sobre os elementos
        var falta_preencher = false;
        $('.meu_grupo').each(function() {
            if (!this.selectedIndex) falta_preencher = true;
        });

        //verifica o resultado
        if (falta_preencher) alert('Preencha todos...')
        else alert('Preencheu todos!');

    })
});

See the jsfiddle working.

The idea is to place a change event in all fields that have the class meu_grupo and, when an event occurs, check that all fields in the same group are duly filled in.

Obviously, the type of validation and the action resulting from all fields being correct is at the discretion of the implementation.

Note that I linked the event change directly to the fields with the class meu_grupo, as this is more efficient than capturing all document events and filtering only the desired fields. Unless you have other reasons to use it on in the document, give preference to specific events. Follow the same example using the on:

$(function() {
    $(document).on('change', '.meu_grupo',  function() {

        //itera sobre os elementos
        var falta_preencher = false;
        $('.meu_grupo').each(function() {
            if (!this.selectedIndex) falta_preencher = true;
        });

        //verifica o resultado
        if (falta_preencher) alert('Preencha todos...')
        else alert('Preencheu todos!');

    })
});

Note also that the validation of my example will make an implicit conversion from the text "0" to false. The effect would be the same if the value of the first element were empty.

  • I like the more generic solution, but your example should use event delegation to meet the requirements of the question.

  • @bfavaretto I see no restriction on the question as to the method of capturing the event. Joao said he did it that way for one of the fields, but he doesn’t know which is the best way. Anyway, I added a few notes regarding why I did it that way.

  • 2

    I understood from the first sentence that the fields are injected into the DOM after the page loading, but the definition of the Listener would be done before (that last part I inferred).

  • @bfavaretto Ah, you’re right, this is probably the reason. I’ll change my answer. Thank you. (I need to sleep more)

Browser other questions tagged

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