Reputation: 51
I have this structure:
<div id="list_articles">
<div id="article">
<label>Select:</label><input type="checkbox" class="checked_art" id="1001" />
<div id="hide" style="display:none;" class="1001">
//Code here...
/div>
</div>
<div id="article">
<label>Select:</label><input type="checkbox" class="checked_art" id="1002" />
<div id="hide" style="display:none;" class="1002">
//Code here...
/div>
</div>
</div>
What I want to do is that when I check my checkbox, get the "hide" according to the checkbox's id, for example: If I check this one:
<input type="checkbox" class="checked_art" id="1001" />
I want to remove the style of
<div id="hide" style="display:none;" class="1001">
I've been trying this way with Jquery:
$(".checked_art").live('click',function()
{
var id = $(this).attr('id');
var checked = $(this).attr('checked');
var a = "#hide ."+id;
if(checked == 'checked')
{
$(a).show();
}
else
{
$(a).hide();
}
}
But it just works with the first element, I want it to do that with all of them, any help? Thanks.
Upvotes: 0
Views: 1002
Reputation: 8348
First of all, .live()
has been deprecated. If you're using a recent version of jQuery, you should use .on()
:
$(document).on("click", ".checked_art", function() {
// ...
});
Also, IDs must be unique. Therefore, you should change the make the "hide" identifier a class
attribute rather than a id
attribute.
Furthermore, your id
and class
attributes should begin with a letter, not a number. You can fix this by prefixing each of your attributes that begin with a number with a common string, such as "e." For example, you would change "1001" to "e1001".
Anyway, your problem is the space between the id
and the class
. This:
var a = "#hide ."+id;
Should be this:
var a = ".hide."+id;
Upvotes: 0
Reputation: 13360
First, change this line to use class rather than id:
<div style="display:none;" class="1001 hide">
Then, change your function to use the class .hide
rather than the id #hide
and remove the space between the .hide
and the .1001
selector (indicating on the same level)
$(".checked_art").on('click',function()
{
var id = $(this).attr('id');
var checked = $(this).attr('checked');
var a = ".hide."+id;
if(checked == 'checked')
{
$(a).show();
}
else
{
$(a).hide();
}
}
However, a simpler code would be (based on your HTML):
$(".checked_art").on('click',function()
{
if ($(this).is(':checked')) {
$(this).next('div.hide').hide();
} else {
$(this).next('div.hide').show();
}
}
Or, even simpler:
$(".checked_art").on('click',function()
{
$(this).next('div.hide').toggle();
}
Upvotes: 0
Reputation: 207963
$(".checked_art").click(function(){
$(this).next().toggle();
});
By the way, IDs must be unique.
Upvotes: 1