2

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!

4
  • 3
    Why are you using div for options? Why not simple radio buttons which are meant for that purpose? Commented Jul 21, 2015 at 6:05
  • Hi, I would like to use DIV for selection.. Just because I customized it on good level and I believe this selection can be possible for DIV elements as well - apart from other options like radio buttons - check boxes etc., Commented Jul 21, 2015 at 6:09
  • Do you want to use them like a link? Commented Jul 21, 2015 at 6:10
  • No, just DIV sections Commented Jul 21, 2015 at 6:11

10 Answers 10

7

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your help!
3

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/

2 Comments

Thanks Venkat, this is a clean solution.. is there a way to accomplish the same using simple javascript ?.. for some reason, I do not want to use Jquery
Thanks Venkat for adding Javascript version :)
2

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)

You shouldn't be using divs as options. This is not semantic. Radios (and checkboxes) are elements which are there for that purpose. divs are meant for dividing your content into sections and that is where you should stop. You use radios and checkboxes for form elements. There are many other problems of abusing elements for things which they are not meant for:

  1. You end up with lot of extraneous code just to force divs into doing what they are not supposed to do. Maintaining state of selection, customizing presentation, etc. This code over a period of time becomes convoluted and difficult to maintain.
  2. You also need extra code to then post the values back to the server-side code along with form data. You will go into hoops to coerce div states into meaningful values, something which form elements provide you with out-of-the-box. UI no longer remains clean.
  3. Imagine some other developer tasked to maintain your code. (S)he will waste a lot of productive time in just trying to decipher where are those magic values coming from. And then making even small changes will be a burden. When you use form elements, all user-collected values are in same place and visible clearly as form elements in code. It then becomes very easy to decipher where all those values are coming from.

Your comment:

I would like to use DIV for selection.. Just because I customized it on good level and I believe this selection can be possible for DIV elements as well - apart from other options like radio buttons - check boxes etc.

Just because you believe that something can be possible, doesn't mean you should be doing it. Yes, it is possible. But, it is not the intended purpose of HTML.


Solution:

I assume that the only reason you want to use divs for options, is that you are able to customize it. Well, you can customize radios and checkboxes too. Using form elements will save you from a lot of code, and also you do not need Javascript at all because the values will be part of the formData and will be available server-side with zero effort.

Just use proper radio (or checkbox if multiple options are needed), add related labels, and then stylize them. That's all to it.

Using Radios:

Javascript used only to display values client-side for demo

Example Fiddle 1: http://jsfiddle.net/abhitalks/xg3dwme7/1/

Snippet 1:

function getOptions() {
    var elems = document.getElementById('myform').elements;
    var sel = elems['myOptions'].value;
    alert(sel);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
ul.mySection { margin: 16px; list-style: none; }
ul.mySection li { margin: 0px 0px; display: inline-block; }
ul.mySection input[type=radio] { display: none; }
ul.mySection label {
    display: table-cell; cursor: pointer;
    width: 200px; height: 50px; 
    vertical-align: middle; text-align: center;
    background-color: rgba(0, 0, 255, 0.4);
}
ul.mySection label:hover { 
    background-color: rgba(0, 0, 255, 1); color: #fff; transition: all 0.25s;
}
ul.mySection input[type=radio]:checked ~ label { 
    background-color: rgba(50, 200, 50, 1); 
}
input#btn { margin: 8px 18px; padding: 8px; }
<form id="myform">
    <ul class="mySection">
        <li>
            <input type="radio" id="r1" name="myOptions" value="Computers" checked />  
            <label for="r1">Computers</label>
        </li>
        <li>
            <input type="radio" id="r2" name="myOptions" value="Electronics" />  
            <label for="r2">Electronics</label>
        </li>
        <li>
            <input type="radio" id="r3" name="myOptions" value="Mechanical" />  
            <label for="r3">Mechanical</label>
        </li>
        <li>
            <input type="radio" id="r4" name="myOptions" value="Electrical" />  
            <label for="r4">Electrical</label>
        </li>
    </ul>
    <input id="btn" type="button" value="confirm" onclick="getOptions();" />
</form>

And if you at all need to change it to multiple selections, you can do so very easily by just changing radio to checkbox without any change to the code and it will all work.


Using Checkboxes:

Javascript used only to display values client-side for demo

*Example Fiddle 2: http://jsfiddle.net/abhitalks/th3yqkq0/4/ *

Snippet 2:

function getOptions() {
    var frm = document.getElementById("myform");
    var chk = frm.querySelectorAll('input[type=checkbox]:checked');
    var vals = [];
    for (var i=0; i<chk.length; i++) {
        vals.push(chk[i].value);
    }
    alert(JSON.stringify(vals));
}
* { box-sizing: border-box; margin: 0; padding: 0; }
ul.mySection { margin: 16px; list-style: none; }
ul.mySection li { margin: 0px 0px; display: inline-block; }
ul.mySection input[type=checkbox] { display: none; }
ul.mySection label {
    display: table-cell; cursor: pointer;
    width: 200px; height: 50px; 
    vertical-align: middle; text-align: center;
    background-color: rgba(0, 0, 255, 0.4);
}
ul.mySection label:hover { 
    background-color: rgba(0, 0, 255, 1); color: #fff; transition: all 0.25s;
}
ul.mySection input[type=checkbox]:checked ~ label { 
    background-color: rgba(50, 200, 50, 1); 
}
input#btn { margin: 8px 18px; padding: 8px; }
<form id="myform">
    <ul class="mySection">
        <li>
            <input type="checkbox" id="r1" name="myOptions" value="Computers" />  
            <label for="r1">Computers</label>
        </li>
        <li>
            <input type="checkbox" id="r2" name="myOptions" value="Electronics" />  
            <label for="r2">Electronics</label>
        </li>
        <li>
            <input type="checkbox" id="r3" name="myOptions" value="Mechanical" />  
            <label for="r3">Mechanical</label>
        </li>
        <li>
            <input type="checkbox" id="r4" name="myOptions" value="Electrical" />  
            <label for="r4">Electrical</label>
        </li>
    </ul>
    <input id="btn" type="button" value="confirm" onclick="getOptions();" />
</form>

Hope that helps.

.

2 Comments

Hi, Thanks for your feedback :)
@SathishPanduga: Glad you found it helpful. Also, note that even hiding the radio/checkbox is not a best-practice. I only quickly demoed it for you. In production quality code, they should be visible (by any UI customization if required). This is also good for accessibility.
1

This is pure JS solution 1. find all div's with class optionsecoptions 2. add click listener to them 3. add active attribute to div with active attribute 4. remove active attribute from other div's 5. add click listener to confirm link,print content of div with active attribute

Demo https://jsfiddle.net/youssefmohamed/ntxuc69a/21/

HTML

<div style="margin-top:10px;" id="container">
                <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>

CSS

#container div[active="active"]
{
    background-color: #226fa3;
    transition: background-color 0.4s ease-in, border-color 0.4s ease-in;
    color:#ffffff;
}
.optionsecoptions
{
    width: 400px;
    height: 40px;
    background: #bbb8b8;
    float: left;
    font-size:20px;
    cursor:pointer;
}
.optionsecoptions:hover,
.optionsecoptions:active {
    background-color: #226fa3;
    transition: background-color 0.4s ease-in, border-color 0.4s ease-in;
    color:#ffffff;
}

JS

    // get all divs with class optionsecoptions
        var options = document.getElementsByClassName("optionsecoptions");
// add click listener to them
        for(var i=0; i<options.length; ++i) {
            options[i].addEventListener("click", function(event){
                if(!this.active) {
                    this.setAttribute("active","active");
                    // remove all active attributes from other divs
                    for(var i=0; i<options.length; ++i) {
                        if(options[i] != this) {
                            options[i].removeAttribute("active");
                        }
                    }
                }
            }, false);
        }
// get confirm link
        var confirm = document.getElementsByTagName("a")[0];
// add click listener to link
        confirm.addEventListener("click", function(event){

            for(var i=0; i<options.length; ++i) {
                if(options[i].hasAttribute("active")) {
                    alert(options[i].textContent);
                    break;
                }
            }
            event.preventDefault();
        }, false);

Comments

0

Give every div an ID, and work according to your ID, i'd recommend using jquery here.

if($("#element").click()) {
  method body. 
}

if you want to use pure javascript, use document.getElementById("Element");

2 Comments

Hi Barr, 'document.getElementById("Element")' can be used to access the element, but how do we persist the DIV selection in this case using javascript ?
Because through this, you can check if the element was clicked. example, if(document.getElementById("Element").click()) { method body }
0

Try below code instead

$(".optionsecoptions").click(function(event){
    alert($(this).html());
    event.stopImmediatePropagation();
});

In this case $(this) will give you the element that you are clicking.

Please not that it needs jQuery file to be included.

Comments

0

Maybe try the following fiddle. Alert is just to show you how the code works. you may use a message span or div and set the text for the div to the selected div's text...

http://jsfiddle.net/ntxuc69a/1/

$( ".optionsecoptions" ).click(function() {
  alert( $(this).text());
    $(this).css('background-color','green');
});

Comments

0

Try like this: Demo

$(document).ready(function () {
    $('.optionsecoptions').on('click', function () {
        $('.optionsecoptions').removeClass('active');
        $(this).addClass('active');
    });
});

CSS:

.active {
    background: red;   

}

Comments

0

I have created a class 'selected' in css and used 'this' operator to find the active class. & added the jquery plugin. and that to the current div and removed from all other div's

JS Fiddle updated

$(function () {
$('.optionsecoptions').click(function(){
    $('.optionsecoptions').removeClass('selected');
    $(this).addClass('selected');
});
});

Comments

0

This function helps you to add Active System quickly.

    function activeSystem(itemsClass, activeClass) {
        var x = document.getElementsByClassName(itemsClass);
        for (var i = 0; i < x.length; i++) {
            x[i].addEventListener("click", function(){
                [].forEach.call(x, function(el) {
                    el.classList.remove(activeClass);
                });

                this.classList.add(activeClass);

            }, false);;
        }
    }

To use this, just call

activeSystem('optionsecoptions', 'active');
activeSystem('gender-item', 'active');

This function remove active class in all elements with your-class and add active class on element on which you click. Create custom .active in CSS to update the UI.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.