Reputation: 25
I'm trying to create a multiple selection checkbox from a dropdown and get the chosen results concatenated by ;
.
my code looks like that:
var myobject = {
ValueA : 'Text A',
ValueB : 'Text B',
ValueC : 'Text C',
ValueD : 'Text D',
ValueE : 'Text E',
ValueF : 'Text F'
};
var select = document.getElementById("rec_mode");
for(index in myobject) {
select.options[select.options.length] = new Option(myobject[index], index);
}
<select id="rec_mode">
</select>
Upvotes: 1
Views: 70
Reputation: 1
Mabye it is half answer but it can help you :)
var myobject = {
ValueA : 'Text A',
ValueB : 'Text B',
ValueC : 'Text C',
ValueD : 'Text D',
ValueE : 'Text E',
ValueF : 'Text F'
};
$(document).ready(function() {
for(index in myobject) {
var temp ="<li><input type='checkbox' value='"+index+"' />"+index+"</li>"
document.getElementById("listOfCheckbox").innerHTML +=temp;
}
});
<div class="mutliSelect">
<ul id="listOfCheckbox"></ul>
</div>
Upvotes: 0
Reputation: 1677
Review the function selectedValue()
, which is fired when the select change its value. Also, for multiple values you must to add multiple
attribute to the select tag.
var myobject = {
ValueA : 'Text A',
ValueB : 'Text B',
ValueC : 'Text C',
ValueD : 'Text D',
ValueE : 'Text E',
ValueF : 'Text F'
};
var select = document.getElementById("rec_mode");
for(index in myobject) {
select.options[select.options.length] = new Option(myobject[index], index);
}
function selectedValue() {
var selectChilds = document.getElementById("rec_mode").childNodes;
var selectedValues = "";
for(var i = 0; i < selectChilds.length; i++){
if(selectChilds[i].selected){
selectedValues += selectChilds[i].value + ";";
}
}
alert(selectedValues.substring(0, selectedValues.length -1));
}
<select id="rec_mode" multiple onchange="selectedValue()">
</select>
If you wish to write the code with checkbox
tags, follow this snippet.
var myobject = {
ValueA : 'Text A',
ValueB : 'Text B',
ValueC : 'Text C',
ValueD : 'Text D',
ValueE : 'Text E',
ValueF : 'Text F'
};
var chbxs = document.getElementById("rec_mode");
for(index in myobject) {
chbxs.innerHTML += '<input type="checkbox" value="' + index + '" /> ' + myobject[index] + '<br />'
}
function selectedValue() {
var selectChilds = document.getElementById("rec_mode").childNodes;
var selectedValues = "";
for(var i = 0; i < selectChilds.length; i++){
if(selectChilds[i].checked){
selectedValues += selectChilds[i].value + ";";
}
}
document.getElementById("result").textContent = selectedValues.substring(0, selectedValues.length -1);
}
<div id="rec_mode" onchange="selectedValue()">
</div>
<p id="result"></p>
Upvotes: 1