Reputation: 2400
i am dealing with got the values using plain Javascript from a list of checkboxes with a select field related to each one.
I have this HTML ( with three checkboxes samples )
<section class="options-list">
<div>
<input type="checkbox" class="cb" value="valueForCheckbox-01" id="cb-01" name="checkboxStatus"/>
<label for="cb-01">Page Load Time</label>
<select id="type-01" name="optionSelected">
<option value="001">001</option>
<option value="002">002</option>
<option value="003">003</option>
<option value="004">004</option>
</select>
</div>
<div>
<input type="checkbox" class="cb" value="valueForCheckbox-02" id="cb-02" name="checkboxStatus"/>
<label for="cb-02">DB Query</label>
<select id="type-02" name="optionSelected">
<option value="001">001</option>
<option value="002">002</option>
<option value="003">003</option>
<option value="004">004</option>
</select>
</div>
<div>
<input type="checkbox" class="cb" value="valueForCheckbox-03" id="cb-03" name="checkboxStatus"/>
<label for="cb-03">Server Response Time</label>
<select id="type-03" name="optionSelected">
<option value="001">001</option>
<option value="002">002</option>
<option value="003">003</option>
<option value="004">004</option>
</select>
</div>
<input type="button" id="save-data" value="Save" onclick="userChoice('checkboxStatus', 'optionStatus')"/>
</section>
And the following JS working to got the checked elements
var checkboxes = [];
function userChoice(checkboxName, options) {
checkboxes = document.querySelectorAll('input[name="' + checkboxName + '"]:checked'), cbSelected = [];
Array.prototype.forEach.call(checkboxes, function(el) {
cbSelected.push(el.value);
return cbSelected;
});
return cbSelected;
}
I'm not sure if that is the best way, but the piece remaining is get the options value and link to the checkbox.
And to end i'm not sure the best way to store these data, what do you suggest ? an array of arrays ?... [[checkboxSelected.value, option.value][checkboxSelected.value, option.value]]
...An array of object... [{state: "checked", option: value}{state: "checked", option: value}]
..or maybe another idea
Upvotes: 0
Views: 746
Reputation: 8589
You can get the select by referencing from each checkbox. Something like cbSelected.parentNode.querySelector('select')
. I'd personally use an array of objects to store the data, but an array of arrays is possible, or an object used as a map.
var model1 = [
{
'type' : 'checkbox',
'id' : '01',
'checked' : true
},
{
'type' : 'select',
'id' : '01',
'value' : 002
}
];
var model2 = {
'01' : {
'checkbox' : true,
'option' : '002'
},
'02' : {
'checkbox' : false,
'option' : 'default'
}
};
Upvotes: 1