views:

50

answers:

4

I have a series of divs that have similar ids with the exception of a unique # at the end (cartbtn0, cartbtn1, etc.). I have created one generic function that will work across all the divs using a wildcard, but I need to be able to capture the unique # of the div that was clicked in order to replace the 0 in #cartbox0:hidden. Can anyone please help?

Sample code:

$("*[class^=cartbtn]").click(function () {  
    $(this).hide();  
    $('#cartbox0:hidden').fadeIn(2000);  
});

<div id="cartbtn0" class="cartbtn0">.....</div>  
<div id="cartbox0>" class="cartbox0" style="display:none;">.....<div>  

<div id="cartbtn1" class="cartbtn1">Text</div>  
<div id="cartbox1>" class="cartbox1" style="display:none;">Text<div>
A: 

You can use:

this.id

inside the click handler.

kgiannakakis
A: 

To avoid having to manipulate the string (you could of course do $(this).attr('id').substring(...), I'd say your best option would be to do:

$(this).find(':hidden').fadeIn(2000);

That will give you the clicked div, if it is hidden. Although I don't quite see why you would want to search for that, since you're always hiding it just before that.

David Hedlund
A: 

Try

$('#'  & this.id.replace('cartbtn','cartbox') + ':hidden').fadeIn(2000);

instead of

$('#cartbox0:hidden').fadeIn(2000);

that should take the div, and replace the name.

astander
A: 

I assume you're dynamically creating these divs. If that's the case, you could add an attribute to them, that holds the number. Then you could access that attribute on click and append it onto the end of the class. This would save you from having to manipulate the class name strings.

$("*[class^=cartbtn]").click(function () {  
    $(this).hide();
    var num = $(this).attr('ref');  
    $('#cartbox'+num+':hidden').fadeIn(2000);  
});

<div id="cartbtn0" class="cartbtn0" ref="0">.....</div>  
<div id="cartbox0" class="cartbox0" ref="0" style="display:none;">.....<div>  

<div id="cartbtn1" class="cartbtn1" ref="1">Text</div>  
<div id="cartbox1" class="cartbox1" ref="1" style="display:none;">Text<div>
munch
If you're going to add attributes to elements, best to use a `data-` prefix. Adding arbitrary attributes to elements has always been contrary to the HTML specification (although tolerated by browsers in reality) causing validation issues. But *finally*, in HTML5, we got the `data-` prefix, which basically means "what follows is not in the spec, don't worry about it." So `data-ref` for instance. That works now, and will validate when the HTML5 validator is working properly.
T.J. Crowder
Right on. Good to know. Thanks. :)
munch