Reputation: 28799
I have a page with a link in it , when pressing the link I want to add new LI to UL using jQuery, I created my jQuery function and it works just one time, I mean, jQuery function works for just on click
$("#addRelation").ready(function (){
$("#addRelation a").css("padding","6px");
$("#addRelation .araNew").bind('click',function(){
$("#addRelation .araNew").hide();
$("#addRelation ul li:last").append('<li> \n\
<p>\n\
<label>Source</label>\n\
<select name="source[]" id="source">\n\
<option>select source</option>\n\
</select>\n\
</p>\n\
<p>\n\
<label>Destination</label>\n\
<select name="destination[]" id="destination">\n\
<option>select destination</option>\n\
</select>\n\
</p>\n\
<p>\n\
<a href="#" class="araNew">new</a> \n\
<a href="#" class="araDel">delete</a> \n\
</p>\n\
</li>');
});
<div class="container" id="addRelation">
<ul class="containerUL">
<li class="containerLI">
<label>Name</label>
<input type="text" name="relationName" class="longInput1"/>
<div id="arSuggestions"></div>
</li>
<li>
<label>Related Concepts</label>
<p>
<label>Source</label>
<select name="source[]" id="source">
<option>select source</option>
</select>
</p>
<p>
<label>Destination</label>
<select name="destination[]" id="destination">
<option>select destination</option>
</select>
</p>
<p>
<a href="#" class="araNew">new</a>
<a href="" class="araDel">delete</a>
</p>
</li>
</ul>
</div>
and also any suggestions for adding li to ul different from my function?
Upvotes: 0
Views: 362
Reputation: 13461
Add your append code inside $.on syntax like this
$("#addRelation").on('click','.araNew',function(){
// add li code
});
Check the working fiddle here
Upvotes: 2
Reputation: 17451
You're hiding the old araNew
and adding a new one without binding the click to it.
Upvotes: 1
Reputation: 165961
The problem is that you are adding a new a
element to the DOM, but the event handler is bound to the old one. You can use event delegation (with the jQuery on
method, or delegate
if you're using a version below 1.7) to capture the click event higher up the DOM tree:
$("#addRelation").on("click", ".araNew", function() {
//Do stuff...
});
This will capture the click event when it reaches the ancestor div
element. It will check to see if the event target matches .araNew
, and if it does it will execute the event handler. This way, the handler will execute no matter which element matching .araNew
you click.
Alternatively, you could simply move the "new" and "delete" links outside of the ul
, instead of creating new ones each time.
Upvotes: 3
Reputation: 25776
That's because you're dynamically inserting the element(s) at a later time. Use .on
to attach the click event handler, this will ensure the event handler is called for dynamically inserted elements as well.
$("#addRelation").on('click', '.araNew', function(){
// code here
});
Upvotes: 2