jquery dynamically change data attribute value and calculate arithmetic operation(addition) -


this script

 $(document).on('click', '.cnt', function(e) {         e.preventdefault();         var wa = $('#te').data('vals');         va = wa + 1;         console.log(va);         $('#te').data('vals', va);         $('#te').attr('data-vals', va);     })   

and here

<a href="" class="cnt">click me</a> <div id="te" data-vals=1>count</div> 

the above script not working expected. please find fiddle here

you can use .attr() instead of .data() using unary plus + before value parse wa value integer in order increase number:

$(document).on('click', '.cnt', function (e) {     e.preventdefault();     var wa = $('#te').attr('data-vals');     va = +wa + 1;     console.log(va);     //$('#te').data('vals', va);    // not updating once     $('#te').attr('data-vals', va); // updating once }); 

updated fiddle


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -