Search code examples
jqueryclickbindhref

Jquery click bind doesn't work second time


i have a strange behaviour with a and with img tag inside.

I have a php page with a table that is a list of records. At the end of every row i have a button for delete row.

This is the code of my table:

<div class='edit' >
    <a id='20' href='#' return;>
        <img src='images/edit.png'  />
    </a>
</div>

Every record, every row of the main table, has the code above, with different id each other.

My script code is:

$("#delete a").click(function(e) {

e.preventDefault();

$('#action').val("delete");
$('#keyAction').val(this.id);

$.ajax({
        type: "POST",
        url: "processAttivita.php",
        data: $("#attivita_form").serialize(),
        error: function(msg) {
            $("#errore").html(msg);
        },
        success: function(msg) {
            // display the errors returned by server side validation (if any)
            ricaricaLista();                

        }
    });     

 // end click delete event  
 });

The first row i try to delete clicking on the image works fine. On the second one it seems that jquery doesn't bind "click" event and default href of a element occurs, remaining on the same page due the "#" in href attribute.

Any ideas why the second time jquery doesn't intercept click on <a> element ?


Solution

  • You're using an ID selector #delete a which will only match one (generally the first) element.

    Try using a class, e.g. .delete a.

    The reason you only get one element is because JQuery optimizes any selector that begins with # passes through to document.getElementById, which only returns 1 element.

    Here's an example of how to use event delegation to achieve the same thing:

    $("#tableid").click(".delete a", function(e) {
        // your code
    });
    

    Your html would need to have an ID on your table and give class="delete" to the container of your delete links.