Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select only one DIV from multiple divs using javascript

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">
        &nbsp;&nbsp;Computers
    </div>
    <div class="optionsecoptions" style="top:151px;">
        &nbsp;&nbsp;Electronics
    </div>
    <div class="optionsecoptions" style="top:212px;">
        &nbsp;&nbsp;Mechanical
    </div>
    <div class="optionsecoptions" style="top:273px;">
        &nbsp;&nbsp;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!

like image 867
Satheesh Panduga Avatar asked May 09 '26 09:05

Satheesh Panduga


2 Answers

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

like image 67
nalinc Avatar answered May 10 '26 23:05

nalinc


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/

like image 36
venkat7668 Avatar answered May 10 '26 22:05

venkat7668