Reputation: 12864
I have a div that contains a number of divs inside it. The divs are used to select a number by the user. When the select a div I make the background color of that div to green.
My problem is how do I write a JQuery selector to give me the index of the div that is selected ie green?
Malcolm
EDIT
var green = "rgb(0, 128, 0)";
function getIndex(selector) {
$(selector).each(function () {
if ($(this).css("background-color") == green)
return $(this).index();
});
return -1;
}
Upvotes: 0
Views: 90
Reputation: 3373
I think this is what you need.
HTML
<div class="container">
<div class="userselect"> </div>
<div class="userselect"> </div>
<div class="userselect"> </div>
<div class="userselect"> </div>
<div class="userselect"> </div>
</div>
CSS
userselect{
width:20px;
height:20px;
background:yellow;
border:1px solid black;
margin:5px;
}
.selected{
background:green;
}
JQuery
$(".userselect").on("click",function(oEvent){
$(".userselect").removeClass("selected");
$(this).addClass("selected");
alert("you clicked : "+$(this).index());
});
Upvotes: 0
Reputation: 5309
Are you looking for this one...
$("div").click(function(){
$("div").css("background","none");
$(this).css("background","green");
var index = $(this).index();
alert(index);
});
Upvotes: 0
Reputation: 29683
Try this DEMO
.green
{
background-color:green;
color:white;
}
JS
$('.parent div').on('click',function(){
$('.parent div').removeClass('green');
$(this).addClass('green');
});
$('#btncli').on('click',function(){
alert($('.parent div.green').index());
});
Upvotes: 1
Reputation: 10447
You should apply a class to "select" a div, then apply styling to that class to make the background clean. Then you can just select the element by the class like this:
$('.my-class')
Upvotes: 0
Reputation: 2647
How are you changing the background color? if you are using $(".yourdiv").css("background-color","green") You should create a css class instead.
.selected{
background-color: green;
}
And then add that class
$(".yourdiv").addClass("selected")
After that, you only need to call the selector like so:
$(".selected")
Upvotes: 1
Reputation: 34905
I assume the background color is applied with a class so:
$("div.green-color").index();
Upvotes: 0