I am working on a script that will collect data-attributes from dynamically changed elements on page, and return this data for further manipulation.
Anything works, except for my function writes data into array only ONE time, and then it won't rewrite array on second, third, etc. use, even if data-attributes of elements have changed.
// checkbox functionality
$(document).on('click', '.myoption', function() {
event.target.setAttribute('data-selected', event.target.getAttribute('data-selected') === 'yes' ? 'no' : 'yes');
$('.myoption').not(event.target).attr('data-selected', 'no');
});
// collect data-attributes of elements and return output
$(document).on('click', '.mybtn', function(e) {
e.preventDefault();
myData = [];
$(".myoption").each(function() {
var id = $(this).attr('id');
var selec = $(this).data('selected');
item = {}
item[id] = selec;
myData.push(item);
});
alert(JSON.stringify(myData));
});
JSFiddle: https://jsfiddle.net/AlpacaLord/9cd3w0zb/
To see the issue, try to check box number 1 for example, and click button; then try to check any other box and click button – you can see that output never changes.
How to force jQuery to rescan DOM and rewrite the array every time when function is called?