I have below code in my HTML which has multiple DIV's, I would like to use these DIV's as options. For this reason, the DIV which is being clicked should be selectable (leaving others non selected - only one should be active) and when I click on Confirm link, the value within the selected DIV should be displayed on message box.
<div style="margin-top:10px;">
<div class="optionsecoptions">
Computers
</div>
<div class="optionsecoptions" style="top:151px;">
Electronics
</div>
<div class="optionsecoptions" style="top:212px;">
Mechanical
</div>
<div class="optionsecoptions" style="top:273px;">
Electrical
</div>
</div>
<a href="#"> Confirm </a>
Here is the demo :
http://jsfiddle.net/sathish_opr/ntxuc69a/
I tried some solution in Jquery, but is this possible using simple javascript ? please help!
You may use addEventListener for a javascript only solution to add/remove a particular class from your <div>.
You would need to iterate over all elements with class .optionsecoptions and attach click event listener on each of them, (or better enclose all <div> in a wrapper and exploit bubbling of click event)
var x = document.getElementsByClassName('optionsecoptions')
for (var i = 0; i < x.length; i++) {
x[i].addEventListener("click", function(){
var selectedEl = document.querySelector(".selected");
if(selectedEl){
selectedEl.classList.remove("selected");
}
this.classList.add("selected");
}, false);;
}
Here's the workingdemo
I added new class name called selected, based on class name you can get the selected item when you click on confirm button at bottom.
$("#container").delegate("div","click",function(e){
$("#container .selected").removeClass("selected");
$(this).addClass("selected");
});
$("#confirm").click(function(){
var selectedTxt = $("#container .selected").text() || "select one opction";
alert(selectedTxt);
});
working URL: http://jsfiddle.net/2yfhh0rs/
PURE JS VERSION
var container = document.getElementById("container"),
confirmBtn = document.getElementById("confirm");
container.addEventListener("click",function(e){
var selectedEl = document.querySelector(".selected");
console.log(selectedEl);
if(selectedEl){
selectedEl.classList.remove("selected");
}
e.target.classList.add("selected");
});
confirmBtn.addEventListener("click",function(){
var selectedEl = document.querySelector(".selected");
alert(selectedEl.innerText);
});
Working DEMO : http://jsfiddle.net/2yfhh0rs/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With