Reputation: 7134
I am loading elements into a div container using Ajax / Request. By default I'm hiding an input box. If a user clicks an edit icon on that div, I want to show the input box. Here is my code:
HTML CODE
<div class='container'>
<input type = 'text' onkeydown='saveFn(event,this)' name = 'editemail' class = 'editemail' style='display:none; height:20px;' />
</div>
JS CODE
$(".container").click(function(){
console.log($(this).find(".editemail").show()); //Note it works fine If i didn't load any new elements into the div.
});
Console Log Output before loading new element into the container.
<input type="text" onkeydown="saveFn(event,this)" name="editemail" class="editemail" style="height: 20px; " value="[email protected]" title="press enter to save">
Console Log Output after loading an element into the container.
<input type="text" onkeydown="saveFn(event,this)" name="editemail" class="editemail" style="height: 20px; display: none; " value="[email protected]" title="press enter to save">
Even though I am also tried to remove the "style" attribute from this element and adding a new style element, it still doesn't work.
Upvotes: 3
Views: 3391
Reputation: 2150
The problem is that the click()
bound is getting lost after an ajax request. In JQuery
you can use .live()
function to get this working however this function is now deprecated and they encourage you to use .on()
or .delegate()
. Personally i've have tons of headecks using .on()
and .delegate()
and rather use the plugin livequery
. With livequery plugin is as simple as:
$(function(){
$('#elementId').livequery('click',function(){
//do something on click
})
});
For more information go to: .livequery() .on() .delegate()
Upvotes: 0
Reputation: 2991
Try this one instead:
$('.container').live('click', function(){
/* Your Code Here */
});
Upvotes: 1
Reputation: 171679
First you should read the jQuery Docs FAQ section: Why_do_my_events_stop_working_after_an_AJAX_request
Use on() to delegate the handler for future elements
$(document).on('click', ".container", function(){
/* your code*/
})
Upvotes: 11
Reputation: 92893
Try this instead:
$(document).on('click','.container',function(){
Upvotes: 4