http://jsfiddle.net/4px4whk0/
I have two question
when first click the
checkbox(a), the firstconsole.logshould be print the dom with emptydata-selected-listattribute, I don't know why it filled what I click already (["a"]) ?
I have to set timeout wrap thecontainer.attr('data-selected-list', selectedList);then it works like what I want.when click other
checkbox(b), I hope it will be["a","b"]store in attribute. but it only store["b"], why?
I hope it can be solve by store data in html attribute not only store in jquery data api
$(document).ready(function() {
$('.container').on('click', 'input[type="checkbox"]', function() {
var container = $(this).closest('.container');
var input = $(this);
console.log(container);
var selectedList = container.data('selected-list');
if (selectedList == '') {
selectedList = [];
}
if (input.is(":checked")) {
selectedList.push(input.val());
}
console.log(selectedList);
selectedList = JSON.stringify(selectedList);
container.attr('data-selected-list', selectedList);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container" data-selected-list="">
<input type="checkbox" value="a">a
<input type="checkbox" value="b">b
<input type="checkbox" value="c">c
</div>