when I use .html() to put data, the jQuery script doesn't work with the new data.
The code is like the this:
<html>
<head>
<script>
$(document).ready(function(){
$("#newhtml").on("click", function(){
alert("I'm the NEW one!");
});
$("#put_new").on("click", function(){
$("#newdiv").html("<input type = 'button' id = 'newhtml' value = 'click on me'/>");
});
});
</script>
</head>
<body>
<div id="newdiv"></div>
<input type="button" id="put_new" value="put new html" />
</body>
</html>
This is a simple example but there is more data I want to put and I want the new elements work with the script in this way.
I tried to search on stackoverflow.com but I didn't find any applicable one.
Thank you so much.
Use this :- http://jsfiddle.net/FQjUZ/
$("#newdiv").on("click", "#newhtml", function(){
alert("I'm the NEW one!");
});
$("#put_new").on("click", function(){
$("#newdiv").html("<input type = 'button' id = 'newhtml' value = 'click on me'/>");
});
Reason is that, for this kind of functionality where elements are added at a later time to the DOM, you need to use delegated event handler, not just binding.
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
Thats because at the time of executing your current .on() statement, the element #newhtml does not exist.
Change your event binding to:
$(document).on('click', '#newhtml', function(){
alert("I'm the NEW one!");
});
The main element(s) you call on() on must be existing at the time of the call. In the second argument, you can specify selector(s) for element(s) that may not be existing at the time of binding.
your event on the newHtml will not work because you attach the event before adding the node to the DOM, so in order for it to work you need to implement your event after the html method is called.
$(document).ready(function(){
$("#put_new").on("click", function(){
$("#newdiv").html("<input type = 'button' id = 'newhtml' value = 'click on me'/>");
$("#newhtml").on("click", function(){
alert("I'm the NEW one!");
});
});
});
Try something like this.
var f00 = "doStuff()";
$("#newdiv").html('<input type="button" id="newhtml" value="click on me" onclick="' + f00 + '"/>');
function doStuff() {
//stuff
}
Related
I output some information with xhr request. On this output I also have a button. I want to bind a function (send e-mail) to it, but for some reason I can't.
Obviously I have included jQuery and I do not get any errors in console. I tried few options already!
button html:
$(document).ready(function(){
$('#sendraportemail').click(function(){
var uroemail = $('#uroemail').val();
console.log(uroemail);
});
});
(function() {
$('#sendraportemail').click(function(){
var uroemail = $('#uroemail').val();
console.log(uroemail);
});
});
$('.sendraportemail').click(function(){
var uroemail = $('#uroemail').val();
console.log(uroemail);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-primary sendraportemail" id="sendraportemail">SEND E-MAIL</button>
I tried binding with $('#sendraportemail') or $('.sendraportemail'). What do I do wrong? Help highly appreciated.
You need to use delegated event binding which is necessary for capturing events on elements that are dynamically added after document.ready:
$(document).ready(function(){
$(document).on('click', '#sendraportemail', function(){
var uroemail = $('#uroemail').val();
console.log(uroemail);
});
});
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
Source: https://api.jquery.com/on/
I have a button that is loaded into my page using ajax:
<button id="submit">Submit</button>
I am using this code on the page that the button is being loaded into:
<script type="text/javascript">
$(function() {
$("button#submit").click(function(){
alert('Submit Clicked');
});
});
</script>
Why is it not detecting the click from the ajax content?
When you attach the click event you attach it to the existent elements in the DOM, when the ajax content comes, new DOM elements are created and the event wasn't attached to them.
One option is to use events delegation a way (but not recommended) to do it is using the document to read the event
$(document).on('click', 'button#submit', function(){
//do something
});
A better way is put the delegation to the element which gets the new content, lets assume is a form with an id formElement, It would be something like
$("#formElement").on('click', 'button#submit', function(){
//do something
});
Using that event delegation the new content from ajax will fire the click event.
PD if you have an ID in a element just use the id, like #submit, It makes a faster selector than tag#id because It used getElementById internaly
In your code you have attached the event handler to buttons before the button is created. You need to attach the handler afterwards. Add the handler in the ajax success() function instead, after you have created the button, and everything will work ok.
Its because its dynamically added button.For that you have to use on() method try following
$(document).on('click', 'button#submit', function(){
alert("hi");
});
Let's say I have a file called example.html that looks like this:
<button>Click me</button>
Now let's say I have another file called index.html that contains this:
$.get('example.html',function(data){
$('body').html(data);
});
How can I do this...:
$('button').click(function(){
$(this).hide();
});
...from my example.html file?
Try this:
$.get('example.html',function(data){
// load
$('body').html(data);
// use
$('button').click(function(){
$(this).hide();
});
});
You need to delegate the event to the static parent:
change this:
$('button').click(function(){
to this:
$(document).on('click', 'button', function(){
because your content is getting loaded via ajax call so initially it was not available in the dom where it is getting loaded so in that case your direct event binding won't work.
To get this work one has to delegate the event to the static parent and in your case you can delegate to body or document itself to get it working.
I think the problem is the click handler registered to the button element is not getting triggered....
The solution is event delegation
$(document).on('click', 'button', function(){
$(this).hide();
});
When you use a normal event registration model, it will register the handlers directly to the targeted which are present in the dom at the point of the handler registration execution. So elements which are added later dynamically will not get those handlers.
The solution to this is to use event delegation, in this model the handler is registered to a ancestor element which will be present when the page is loaded with the a selector to filter out the source element. This makes use of event propagation - events happening in an element is propagated to all the ancestor elements(there are few exceptions like focus event). So an event happening in an element gets propagated to the ancestor element in one of them the handler is registered then the events source element(event.target) and its ancestors is matched against the selector passed as the second parameter, if it is satisfied then the handler is executed.
I am a bit confused, I have a bunch of elements that get added via jquery using a ajax call and I want to attach a click handler to them (there could be a lot).
But I have no idea how to even begin this, I looked at .on and it is really confusing. I want to attach a click event handler for a certain class so that when I click on it, I get the this.id and then do stuff with it.
What you're trying to do is called event delegation.
You want to set the event listener on a higher element in the DOM that'll never change, but only fire off the event handler if the child element that has been clicked matches a specific selector.
Here's how it's done with jQuery's .on():
$(document).on('click', '.your-selector', function(){
alert(this.id);
});
P.S. You could probably apply the event listener to an element lower down in the DOM tree...
This will get you the id of a clicked element with the class "test"...
$(".test").on("click", function() {
var id = $(this).attr("id")
});
You'll need to run that after the ajax call returns. It will only bind the click event to elements that exist when it runs, so it's no good at document.ready.
I would like to delegate the event one for the click. Does anyone know if it is possible to do it?
I'm going to assume that you want the event to fire only once PER matched element rather than unbind entirely on the first click.
I'd implement it like so:
$('#container').delegate('.children', 'click', function() {
if($(this).data('clicked')) {
return;
}
// ... your code here ...
$(this).data('clicked', true);
});
This will fire only once per element. Technically, it fires everytime but is flagged the first time it is clicked so the code will not execute again.
The inherent problem of simulating a .one() handler w/ delegate is that using .one() each element that was matched in the selector is bound its own event handler. So when it is fired for the first time it unbinds/removes the handler from that element. You can't do that with .delegate() because only a SINGLE handler is being used for ALL the matched elements.
While the code above simulates it perfectly, it is still somewhat hackish because it doesn't literally do the same thing that .one() does (unbinding an event handler).
Since this post is a few years old, I just wanted to provide a complete updated example for more contemporary readers (2015). The logic is no different from the other answers here, but jQuery's methods have evolved since 2011. Specifically:
As of jQuery 1.7, .delegate() has been superseded by the .on() method.
jQuery delegate()
// define output element
var $output = $('div#output');
// attach delegated click handler
$(document).on('click', 'button', function() {
// define clicked element
var $this=$(this);
// if this element has already been clicked, abort
if ($this.data('clicked')) {
return false;
}
// perform click actions
$output.append("clicked " + $this.html() + "<br />");
// mark this element as clicked
$this.data('clicked',true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>One</button>
<button>Two</button>
<button>Three</button>
<div id="output"></div>
I'm sure there is a neat way of doing it, but a simple way to do it would be something like this:
<script>
$(document).ready(function(){
$("#container").delegate('.clickers', 'click', function(){
if($(this).data("clicked")==null){
$(this).data("clicked", "true");
$("#container").append($(this).html());
}
});
});
</script>
<div class="clickers" clicked="false"></div>
<div class="clickers" clicked="false"></div>
EDIT: Thanks to the comments below I decided to use data, now this doesn't screw the DOM all up for w3c standards.