Reputation: 1483
Iam trying to do multiple select with JavaScript. but can't working.how can i fix this? Iam done it in following way
var expanded = false;
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
.multiselect {
width: 200px;
}
.selectBox {
position: relative;
}
.selectBox select {
width: 100%;
font-weight: bold;
}
.overSelect {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
}
#checkboxes {
display: none;
border: 1px #dadada solid;
}
#checkboxes label {
display: block;
}
#checkboxes label:hover {
background-color: #1e90ff;
}
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select>
<option>check box1</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<label for="one"><input type="checkbox" id="one" />First checkbox</label>
</div>
</div>
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select>
<option>check box2</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<label for="one"><input type="checkbox" id="one" />First checkbox</label>
</div>
</div>
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select>
<option>check box3</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<label for="one"><input type="checkbox" id="one" />First checkbox</label>
</div>
</div>
Upvotes: 1
Views: 448
Reputation: 9900
you cannot have same id for multiple elements .it's invalid . however when you call getElementById()
1st element is taken .that's why in your example only 1st element expand and collapse .
here is example .
in this example i pass a parameter to showCheckboxes
methods.so we can select correct checkboxes
.also we have to store state of 3 elements individually.
https://jsfiddle.net/93894gbs/5/
js
var expanded = [false, false, false];
var checkboxes;
function showCheckboxes(i) {
checkboxes = checkboxes || document.getElementsByClassName("checkboxes");
if (!expanded[i]) {
checkboxes[i].style.display = "block";
expanded[i] = true;
} else {
checkboxes[i].style.display = "none";
expanded[i] = false;
}
}
Upvotes: 1
Reputation: 231
Also you can pass "event" attribute while calling the handler like :
div class="selectBox" onclick="showCheckboxes(event)"
and change javascript like :
var expanded = false;
function showCheckboxes(ev) {
console.log("ev", ev);
var checkboxes = ev.currentTarget.parentElement.lastElementChild;
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
Upvotes: 0