hey all i am appending a form to a page on click the form has some text boxes and i need to add event listner like on keypress but the function dosent works dont know where is the problem the function works well everywhere but not for this form here is the code.
appending the form
function activityCHART(thisobj){
var theidis=$(thisobj).attr("id");
$("#FULL_FADE").fadeIn();
$.ajax({
type: 'post',
url: 'newpage.php',
data:{'actde':theidis},
success: function(dataa){
$("#the_APPEDEDr5").empty().append(dataa);
}});}
newpage this textbox is present and some more text areas
<input type="text" name="deptname" placeholder="department name" id="detp_names09o" class="TEXTNAME_o909ioi"/>
add this event listner
$('#detp_names09o').keypress(function (e) {
alert('ok');});
these are some script links
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
i think there are some script link problem
alert comes when i does it like this onkeyup="thisisfun();" function thisisfun(){ alert('ok'); }
You should use live(), delegate() or on() to attach event listeners to dynamically added DOM elements. bind() and keypress() doesn't work for elements that are dynamically added to DOM[see this]
$('#detp_names09o').live("keypress",function (e) {
//do some stuff
});
.on() is mostly syntax sugar that can mimic .live(), or .delegate() depending on how you call it.
$('#detp_names09o').on("keypress",function (e) {
//do some stuff
});
Also, you have specified two different versions of jQuery. Though CDN's do have some advantages over locally referenced libraries, they might break your code at-times.
If thats the reason you've referenced to local jQuery file(along with CDN version), you might consider looking at CDN fallbacks. In either case, you should be careful about the version you are using.
Cheers!
To attach event to dynamically added elements,
Try binding the event using 'bind'
$('#detp_names09o').bind("keypress",function (e) {
alert('ok');
});
or use 'on'
$('#detp_names09o').on("keypress",function (e) {
alert('ok');
});
Also you dont require two versions of jquery in your page, also make sure this id is not duplicated
use onkeyup,.. attribute inside the element and call the function like this
<input type="text" name="deptname" placeholder="department name" id="detp_names09o" class="TEXTNAME_o909ioi" onkeyup="functionName()"/>
in javascript
function functionName(){
//your code
}
First of all you should decide what do u want to use, keyup or keypress ? For example if you want to use keyup and you are using jquery version greater than 1.7 then use
$(document).ready(function () {
$('#element').on("keyup",function () {
alert('result ok');
});
});
else u can use
$(document).ready(function () {
$('#element').live('keyup', function() {
alert('result ok');
});
});
Make sure that you are calling working script (check your script link), try not to make duplicate ids of elements instead use class and avoid using inline use of javascript. Happy Coding !
Related
I want to be able to assign a function to keypress of elements that don't exist when the DOM loads. In jQuery the code I had is like this
$(document).on('keypress', '.sc-chat-window .sc-user-input--text, #waste-form input,#address,.waste-wise-container .form-control,.widget-box .form-control,#aria-main-search-form-field,#footer-search-field,#aria-feedback-form-field', function(e) {
updateLastTypedTime();
});
It worked fine, but the problem is I can't use jQuery anymore and I would like to use Pure JavaScript this is what I have. The issue is that some elements don't exist yet so when this runs, it doesn't add the eventListener to the selectors.
JS:
var keyPressElements = document.querySelectorAll('form[id="4840400"],#waste-form input,#address,#aria-main-search-form-field,#footer-search-field,#aria-feedback-form-field');
keyPressElements.forEach(function(elem) {
elem.addEventListener('keypress', function() {
updateLastTypedTime();
});
});
How can I fix this issue?
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I am working on a C# Razor site and I am POSTing from a boostrap modal which then returns a new view and model. To reload the entire page with the response, I am using the following line within this code block.
$("html").html(response);
function addDevice(e) {
e.preventDefault();
var ID = $("#txtNewDeviceID").val();
var Name = $("#txtNewDeviceName").val();
$.post('#Url.Action("AddDevice", "Devices")', { 'DeviceID': ID, 'DeviceName': Name }, function (response) {
$('#newDeviceModal').modal('hide');
$("html").html(response);
AttachBindings();
});
}
Here is the code behind AttachBindings():
function AttachBindings() {
$(document).on('click', 'table tr', {}, tableClick);
$(document).on('keyup', '#search', {}, search);
$(document).on('click', '#btnAdd', {}, function (e) {
addDevice(e);
});
$(document).on('click', '#btnRemove', {}, function (e) {
removeDevice(e);
});
$(document).on('click', '#btnUpdate', {}, function (e) {
updateDevice(e);
});
}
Unfortunately AttachBindings() is never hit and I can't seem to find a way to reattach these events. The only event that seems to work is keyup which is attached to #search. Any ideas on how to fix this?
Try using live function and call it on document.ready
As per the details provided in the documentation for LIVE:
Description: Attach an event handler for all elements which match the
current selector, now and in the future.
Hence, even if an element is added later in the DOM, the event will be triggered by that element
Whereas, in the case of ON, it will be added to the present elements only:
Description: Attach an event handler function for one or more events
to the selected elements.
So, calling it once, after document is ready and bind the events using bind or live will do the magic for you.
I doubled checked this morning and the events are being hit the way I have it. The real issue is the bootstrap modal that I have on the page does not work if the DOM has been updated. It looks like I will need to reconnect the data-toggle and data-dismiss events. I'm guessing bootstrap does this in the background when the page first loads.
Also the .Live method is deprecated according to the JQuery documentation.
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event >handlers. Users of older versions of jQuery should use .delegate() in preference >to .live().
Also AttachBindings does not need to be called more than once. My code updated looks like this now:
function addDevice(e) {
e.preventDefault();
var ID = $("#txtNewDeviceID").val();
var Name = $("#txtNewDeviceName").val();
$.post('#Url.Action("AddDevice", "Devices")', { 'DeviceID': ID, 'DeviceName': Name }, function (response) {
$('#newDeviceModal').modal('hide');
$("html").html(response);
});
}
I actually got some problems with my script: indeed it needs 2 clicks to work in a click event. The script is this:
$('td#td_new').live('click', function() {
$.ajax({
type: 'GET',
url: 'add_hobby.php',
data: { hobby: $('#ricerca_interests').val() },
success: function(msg) {
nuovo_hobby="<tr id='hobby' class='checked' selezionato='si' hobby_id='"+msg+"' ><td id='hobby' width='179px'><div id='nome_hobby'>"+$('#ricerca_interests').val()+'</div></td></tr>';
$(nuovo_hobby).appendTo("#interessilista");
$('tr#new_hobby').hide().remove();
},
error: function() {alert("Error. Try later.");}
});
});
As of jQuery 1.7, the .live() method is deprecated. you should Use .on() to attach event handlers.
it doesn't seems that your code generate something that can cause a second click need... but try changing-
$('td#td_new').live('click', function() {
to
$(document).on('click','#td_new', function() {
then open firebug or add a console.log('something') in the success: part - and make sure that the ajax request finishes as wanted and not continuing to run.
other then that we need some more code...
have fun.
EDIT:
I tried to understand what you are trying to do according to the code you upload, but
there is noway to test it, so here are some insights for you:
Include your source scripts (jquery + UI etc) in the head section.
Remove jquery.min... source - you don't need it because you include the full script any way.
I recommend upgrading to jquery 1.9... you are using 1.7.2
When using same identifier over different elements you should use class not id to declare them.
I recommend you to attach the click event to the div add_hobby as a class and not to the td.
Here is a small demo of the usage of on() and appending code to your page:
jsfiddle Demo
Now feel free to direct me to your exact problem.
So I'm currently using .append() to add a feature to all of the posts on a webpage, but when additional posts are loaded on the page, the appended features aren't included in the new content — I'm trying to come up with a way to make sure all of the new content has the appended feature too.
$(this).append('<div id="new_feature></div>');
Something like this?
$(this).live().append('<div id="new_feature></div>');
Maybe there's a way to make it constantly appending in a loop perhaps?
There is DOMNodeInserted event:
$('button').click(function() {
$('#appendme').append($('<div class="inner">').text(Math.random()));
})
$('#appendme').on('DOMNodeInserted','.inner',function() {
console.log(this);
});
DEMO
update: this seems not works in IE, try propertychnage event handler also ($('#appendme').on('DOMNodeInserted,propertychange') but i not sure, have no IE to check this right now.
update2: Domnode* seems deprecated according to mdn, they tell to use MutationObserver object instead
update3: seems here is no very crossbrowser solution for MutationEvents, see this answer, so my suggestion would be use code above, if event supported and fallback to setTimeOut or livequery option.
update4:
If you depend only on .append() you can patch jQuery.fn.append() like this:
jQuery.fn.append=function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.appendChild( elem );
$(elem).trigger('appended');
}
});
};
$('button').click(function() {
$('#appendme').append($('<div class="inner">').text(Math.random()));
})
$('#appendme').on('appended','.inner',function() {
console.log(this);
});
DEMO2
may be more correct is to spoof jQuery.fn.domManip like here
jQuery documentation:
Use of the .live() method is no longer recommended since later versions of jQuery offer better methods that do not have its drawbacks.
You can use setTimeout() function that can check for new <div>s every n milliseconds.
$(function(){
setInterval("Check4NewDivs();",1000);
});
So say this is a div with class="comment newdiv", so when it appears on the page for the first time, it has the class newdiv that will let the function know it was just dynamically created.
function Check4NewDivs(){
$(".comment .newdiv").each(function(){
$(this).append('<div class="new_feature"></div>').removeClass("newdiv");
});
}
It's append not appened.
live is a deprecated event handler. It's not used this way. use on instead.
http://api.jquery.com/live/
So, the following code will run when you click selector.
$(document).on('click', 'selector', function() {
$(this).append('<div id="new_feature></div>');
});
No, there is no standard way to do it like that. There was a proposal of the events that would be fired whenever the DOM elements are inserted etc., but you cannot rely on that.
Instead rely on either:
(preferably) callbacks - just invoke function ensuring existence of such appended snippets, whenever you pull something (but after you successfully pull it from server and insert into DOM, not sooner), or
constant checks - like using in setInterval() or setTimeout(), but this would be unnecessary processing and you will never get instant append, unless you will perform processing-heavy checks all the time,
use the on load function:
$(item).on('load',function(){
$(this).append('<div id="new_feature"></div>');
});
This will add append the item as a callback once the item has been loaded. I would also choose some sort of dynamic ID creator rather than always append stuff with the same ID, but thats just me.
you must bind to an element that already exists on the page. i have written an example where i make appended content live.
DEMO on JSFiddle
HTML
<div id="container">
<div id="features">
</div>
<br />
<a href='#' id='clickme'>click me to add feature</a>
</div>
JS
$(function() {
$('#clickme').on('click', function(e) {
$('#features').append('<div class="new_feature">new feature</div>');
});
$('#features').on('click', '.new_feature', function() {
alert('i am live.');
});
});
After initialize js I create new <div> element with close class and on("click") function doesn't work.
$(document).on('click', '.post-close', function () {
alert("hello");
});
but on('hover') work perfectly.
$(document).on('hover', '.post-close', function () {
alert("hello");
});
but I need to make it work on click.
It's because you're not preventing the default behaviour of the browser. Pass e into your handler and then use e.preventDefault()
$(document).on('click', '.post-close', function (e) {
e.preventDefault();
alert("hello");
});
Edit
Also, bind the handler before creating the new <div>
why not use something like
$('.post-close').click(function(){
//do something
});
If the element was added dynamically use:
$(document).on('click', '.post-close', function(){
//do something
});
edit:
like danWellman said, you can add the preventDefault IF you want to make sure no other code is executed. otherwise use the code above.
edit2:
changed the .live to .on
It's an old post but I've had a exactly same problem (element created dynamically, hover works, but click doesn't) and found solution.
I hope this post helps someone.
In my case, I found ui-selectable is used for parent element and that was preventing from click event propagate to the document.
So I added a selector of the button element to ui-selectable's 'cancel' option and problem solved.
If you have a similar probrem, check this
Try turn of libraries for parent element
You're not using stopPropagation() in parent element ?