Reputation: 184
I am trying to make a custom select just like this, but without jquery (I just dont want to import a whole new library for one single thing). I made it until this, but I dont know how I can make the selection with regular JS. How can I select something from the list?
Upvotes: 0
Views: 2405
Reputation: 45121
Listen to clicks on your div#options
. Demo
function choose(ev, el) {
var options = el, target = ev.target,
value = ev.target.innerHTML;
options.setAttribute('class', 'hidden');
options.parentElement.querySelector('.label').innerHTML = value;
}
<div id="options" class="hidden" onclick='choose (event, this);'>
Side notes. I don't recommend to use inline handlers. Use addEventListener
instead.
Upvotes: 1
Reputation: 43156
If you just want to show the selected item in the dropdown,
You need to wrap the text to be displayed inside a <span>
as follows
<div class="label"><span>Select Element</span><b class="button">▾</b>
</div>
Then you can change it's innterHTML
to display the selected item using the following js:
var dd = document.querySelector('.label span');
var options = document.querySelectorAll('div.hidden ul li');
for (var i = 0; i < options.length; i++) {
options[i].onclick = select;
}
function show() {
var selectbox = document.getElementById("options");
if (selectbox.className == "hidden") {
selectbox.setAttribute("class", "visible");
} else {
selectbox.setAttribute("class", "hidden");
}
}
function select() {
dd.innerHTML = this.innerHTML;
}
Upvotes: 1
Reputation: 225
You need to define an onclick handler of your li
elements. Either in HTML, or in JS by looping through children of div
container with li
elements http://jsfiddle.net/rWU5t/2/
If you want fancy item highlights on mouse hover, you also need to define onmouseover
and onmouseout
handlers.
Upvotes: 0