JQuery click event not working in bootstrap modal

afaolek picture afaolek · Mar 4, 2014 · Viewed 46.4k times · Source

I have this line of code in my page:

<div id='data'>...</div>      
<a id='addMore' href='#'>Add more </a>   

This line is actually in a bootstrap modal. I want that when a user clicks it, I want the div above it cloned. The issue is not the code for the cloning but that the click event is not even raised. In my .js file, I have this:

$('#addMore').click (...)

The ellipsis is for the code for preventing defaults and cloning. I tried testing with an alert. It still didn't work. I don't know why.

I discovered that if I added onClick='alert(...) in the tag, it worked.

Can anyone help?

This is the HTML of the modal (Wouldn't mind if anyone helped with formatting. I know it's a mess):

<div id="addEmailModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="addEmailLabel" aria-hidden="true">   
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times; </button> 
        <h3 id="addEmailLabel">Add Email</h3>
    </div>
    <div class="modal-body">
        <div id="emailData">
            <input type="text" placeholder="Name (optional)" class="input-xlarge" />
            <input type="email" placeholder="Email" />
        </div>
        <a id="addMore" href="#">Add more&hellip;</a>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button class="btn btn-primary" id="btnAdd">Add</button>
    </div>
</div>

Answer

Luis.Andrade picture Luis.Andrade · Mar 4, 2014

Try event delegation - jQuery's .on() method.

If the event is not working it may be because your tag <a id='addMore' href='#'>Add more </a> is added after the pages loads. You can catch the event with his parent container (note: the parent should already exist in the DOM when the pages loads). Try this:

$(document).ready( function () {
    //Search the parent class, id, or tag and then try to find the <a id="addMore"></a>  as a child
    $('.parent #addMore').on('click', function () {
        alert('addMore click event');
    });
    //Try too with the specific tag
    $('a#addMore').on('click', function () {
        alert('addMore click event');
    });
    //And try too with the specific tag
    $('a #addMore').on('click', function () {
        alert('addMore click event');
    });

});