javascript – How to count state changes in fields with certain class inside a function?


How do I count how many changes occur in all fields of a form with a certain class?

Update: What I want to know is if there was any change in each field ( one ), not how many times there was change in each field (even if the user changes the option, it only counts as once – the first time…). In short, just how many fields with the class in question have been modified once (at least).

For example:

$("select, input").one('change', function () {

    var totalSelect = $('select').length;
    var totalInputs = $('input').length;
    var ocultosOuOpcionais = $('.ocultosOuOpcionais').length;
    var ocultosOuOpcionaisMudados = ?????
    var total = (totalInputs + totalSelect + ocultosOuOpcionaisMudados) - ocultosOuOpcionais;

Every time there is a change of state in some of the fields with the .ocultosOuOpcionais class, I want to update the ocultosOuOpcionaisMudados variable. How can I do this?


You can use data-attributes to "store" the element's state. For example, having an element ( input, select, textarea ) with the data-foi-modificado attribute:

<input type='text' data-foi-modificado />

And with JQuery you can change this property:

$('input').one('change', function(){
  $(this).data('foi-modificado', true);

Later you can make a filter or use the selector itself to get only the elements that have foi-modificado = "true" . Here's an example testing some elements:

 $(function(){ // Quando houver mudança ou perder o foco, o atributo 'foi-modificado' // passará a ter valor 'true'. $('.ocultosOuOpcionais').one('change', function(){ $(this).data('foi-modificado', true); }); $('button').on('click', function(){ // Filtrando todos em que 'foi-modificado' é true. var modificados = $('.ocultosOuOpcionais').filter(function(){ return $(this).data('foi-modificado'); }); var mensagem = 'Modificados: '; modificados.each(function(indice, elemento){ mensagem += $(elemento).prop('name') + ', '; }); alert(mensagem); }); });
 span { display: inline-block; width: 100% }
 <script src=""></script> <span> 1. <input class='ocultosOuOpcionais' type='text' name='1' data-foi-modificado/> </span> <span> 2. <input class='ocultosOuOpcionais' type='number' name='2' data-foi-modificado/> </span> <span> 3. <input class='ocultosOuOpcionais' type='color' name='3' data-foi-modificado/> </span> <span> 4. <input class='ocultosOuOpcionais' type='tel' name='4' data-foi-modificado/> </span> <span> 5. <select class='ocultosOuOpcionais' name='5' data-foi-modificado> <option selected>A</option> <option>B</option> </select> </span> <span> 6. <input class='ocultosOuOpcionais' type='radio' name='6' data-foi-modificado/> </span> <span> 7. <input class='ocultosOuOpcionais' type='checkbox' name='7' data-foi-modificado/> </span> <button>Quem foi Modificado?</button>
Scroll to Top