Search code examples
jqueryjquery-selectors

Jquery trying to work with dynamic id's with onclick event


The problem I'm having is that when I click on the LIKE div it opens all textboxes

It needs to display only the one textbox on the click event.

Here is the example html:

<div id="sublike-1">Like</div>
<div id="sublike-form-1"><input type="text" /> Save</div>

<div id="sublike-2">Like</div>
<div id="sublike-form-2"><input type="text" /> Save</div>

<div id="sublike-3">Like</div>
<div id="sublike-form-3"><input type="text" /> Save</div>

My Jquery:

// Display Sub Like form
$(this).find("div[id^='sublike-']").live('click', function(){
 $("div").find("div[id^='sublike-form-']").toggle();
});

What can I do so that it does not open both textboxes at the same time, must I change my html div's, my jquery or both?

Thanks


Solution

  • If you're absolutely sure that every textbox will be next to the "Like" element, you can use siblings or next:

    $(document).find("div[id^='sublike-']").live('click', function(){
        $(this).siblings("[id^='sublike-form-']:first").toggle();
    });
    

    But if textbox might be "far" from the Like element, you can parse the id:

    $(document).find("div[id^='sublike-']").live('click', function(){
        var num = this.id.split('-')[1];
        $('#sublike-form-' + num).toggle();
    });
    

    Check this example: http://jsfiddle.net/marcosfromero/ZbTzN/