problems creating event listeners dynamically

2

link

JQUERY / Javascript

verificaCamposRepetidos(".teste", array1);
verificaCamposRepetidos(".teste1", array2);

HTML:

<p id="parte1">
    <span>VALORES de 1 a 3</span><BR/>
    <input type="text" class="teste"><BR/>
    <input type="text" class="teste"><BR/>
    <input type="text" class="teste"><BR/>
</p>
<p id="parte2">
    <span>VALORES de 1 a 5</span><BR/>
    <input type="text" class="teste1"><BR/>
    <input type="text" class="teste1"><BR/>
    <input type="text" class="teste1"><BR/>
    <input type="text" class="teste1"><BR/>
    <input type="text" class="teste1"><BR/>
</p>

The problem is occurring when I am going to type in the block ( #parte1 ), it is speaking to enter numbers of 1 à 5 and not 1 à 3 , it seems that it only validates the last function that was added. .. (% with%)

    
asked by anonymous 28.10.2015 / 01:18

2 answers

1

Your problem is happening because of the variable totalPerguntas that is getting the value of the last call of the function verificaCamposRepetidos(); to solve this, just descend the assignment of the variable to the event of .on() as below:

$(element).on("change", function () {
        valorAtual = $(this).val();
        totalPerguntas = $(element).length;
        //Resto da lógica
});

Follow the jsfiddle updated.

    
28.10.2015 / 01:39
0

Yesterday afternoon I came to mind to stop writing both the same js code. And it was there that I discovered a wonderful thing to use (it complicates a bit at first to understand, but then it goes) ...

<div> Menu
<ul>
    <li data-method="abreTela"> Menu 1</li>
    <li data-method="abreTela2"> Menu 2</li>
    <li data-method="abreTela3"> Menu 3</li>
</ul>

With this HTML, in other times I would have something similar to this in my js to assign the events.

var tela = document; //ou outra logica para definir a tela e context atual..
tela.querySelectorAll('ul li')[0].addEventLis ....
tela.querySelectorAll('ul li')[1].addEventLis ....
tela.querySelectorAll('ul li')[2].addEventLis ....

// ou algo semelhante a isso recuperando por id, ou class, ou afins ...

However, when an eventListener is added to the parent object div , when clicking on child objects, the event is also triggered ...

So, just implement the logic to define the execution according to what was clicked. Here is an example showing ..

Added the eventListener on the parent object, and on the Menu.actions function, it performs the processing.

link

    
28.10.2015 / 03:59