user1069516
user1069516

Reputation: 463

jquery click() doesn't work

I have a problem with jQuery click() function.

I use this function to programatically click on a link which calls an ajax function that adds a new object to the database.

When I submit my form, a tr is added in the object datatable for my new object with new link and I want to programatically click on this new link to load object properties and display them.

The problem is that the new tr with td and link doesn't exist in DOM and the function $.('#elem').click') doesn't work.

I saw in others post that I have to bind click event with the new .on function like this :

$('#parent-items').on('click', 'elem', function() {
   // [...]
});

I don't know what I have to write in place of [...], at the end of my javascript code, I call the click function like this :

$('#myelem').click();

Thanks for your help

Upvotes: 0

Views: 267

Answers (1)

Taai
Taai

Reputation: 2760

Not that hard, actually. :)

<table id="list">
    <tr>
        <td>John</td>
        <td><a class="btn-hi">Say Hi!</a></td>
        <td><a class="btn-bye">Say Goodbye!</a></td>
    </tr>
    <tr>
        <td>Lucy</td>
        <td><a class="btn-hi">Say Hi!</a></td>
        <td><a class="btn-bye">Say Goodbye!</a></td>
    </tr>
    <tr>
        <td>Sam</td>
        <td><a class="btn-hi">Say Hi!</a></td>
        <td><a class="btn-bye">Say Goodbye!</a></td>
    </tr>
</table>

<script>
$('#list').on('click', 'a', function() {
    // Wrap the clicked <a> element with jQuery
    var $this = $(this);

    // Get the parent <tr> element
    var $tr = $this.closest('tr');

    // Get all (direct) children elements (<td>) that are inside the current <tr> element
    var $tds = $tr.children();

    // Get the text from the first <td> element in the current row
    var name = $tds.eq(0).text();

    // Get the type (class name) of clicked link
    var type = $this.attr('class');

    if (type == 'btn-hi') {
            alert( 'Hi, ' + name + '!' );
    } else if (type == 'btn-bye') {
            alert( 'Goodbye, ' + name + '!' );
    }
});
</script>

Have a look at this demo in JSBin: http://jsbin.com/welcome/38776/edit

The click event will get executed every time when user clicks on any <a> element that is inside <table id="list"> element. It's called "event delegation" - http://api.jquery.com/delegate/

So, you can dynamically add more rows to the table and everything will still work.

Upvotes: 1

Related Questions