I have a group of checkboxes and I want to add their values which contains a pair of numbers to an array, then use them. The problem is array takes only value of last checkbox. I struggled a lot but couldn't figure it out.
https://jsfiddle.net/zfwbtomu/
HTML:
<div class="scrolly-option" id="input-option20">
<div>
<label>
<input type="checkbox" name="option[20][]" value="20,64">
<span>Mint</span> </label>
</div>
<div>
<label>
<input type="checkbox" name="option[20][]" value="20,63">
<span>Maroon</span> </label>
</div>
<div>
<label>
<input type="checkbox" name="option[20][]" value="20,62">
<span>Ecru</span> </label>
</div>
</div>
<input type="checkbox" class="option1" name="" value="" />
<div class="result"></div>
<button type="button" class="button-cart">ADD</button>
JS:
$('.button-cart').on('click', function(e) {
e.preventDefault;
var firstoptoins = [];
$(".scrolly-option input[type=checkbox]").each(function () {
if ($(this).prop('checked')) {
var arr = $(this).val().split(',');
firstoptoins[arr[0]] = arr[1];
}
});
console.log(firstoptoins);
$('.scrolly-option .checkbox input[type=checkbox]').prop("checked", false);
$.each(firstoptoins, function (o, v) {
$('.option1').attr("name", 'option[' + o + '][]');
$('.option1').attr("value", v);
$('.option1').prop('checked', true);
console.log('o: ' + o + ' v: ' + v);
});
});
20as index to all of the element on the array and that is the reason why you are only getting the last value.valueasindexfor thefirstoptionsarray so all values will be copied to same index