jQuery - bind function to button within xhr output - javascript

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/

Related

How can I use jquery on a html document which has been loaded into another html document?

I have a heading.html file that is being loaded into my index.html.
heading.html
<header id="header">
<div class="logo"></div>
<nav>
Home
About Me
Why Me?
Contact
</nav>
</header>
Then in my javascript file where I am loading in this file, it doesn't let me do any other functions.
functions.js
$( document ).ready(function() {
$(function(){
$("#includedHeader").load("/assets/_includes/header.html");
});
$(function(){
$("#includedFooter").load("/assets/_includes/footer.html");
});
$(function(){
$("#includedWhyme").load("/assets/_includes/why-me.html");
});
$(".slide-section").click(function(){
alert('clicked');
});
});
As you can see I'm trying to make a alert popup just to test if it is working but it doesn't.
Is there a way where I can still use other functions on these html files that are being loaded.
When you're binding the event like this $(".slide-section").click(), the element is not there yet. The .load() is still grabbing the contents from the server.
You can, however, use on method in the document (delegated events). It does a live event attachment (the event will be catched even if the element only exists in the future).
From the .on() docs:
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.
Another suggestion (if I might) is to remove $(function(){} from around your load calls. $(handler) is a shorthand for $(document).ready(handler). So, as if you're calling it once, you don't need them anymore.
So, my suggestion would be something like this:
$( document ).ready(function() {
$("#includedHeader").load("/assets/_includes/header.html");
$("#includedFooter").load("/assets/_includes/footer.html");
$("#includedWhyme").load("/assets/_includes/why-me.html");
});
$(document).on("click", ".slide-section", function(){
alert('clicked');
});
Don't Use directly click() method.. it would not work if the content is not already in the document..instead of this use .on() method to specifie click method its delegate have the advantage that they can process events from descendant elements that are added to the document at a later time.
so i from my point of view use following-
$(document).on("click", ".slide-section", function(){
alert('clicked');
});

Click function not working in .each() function

I want to use click() as eventhandler and that event handler is not working you can see code below
$('.ajax-close').click(function( event ){
event.preventDefault();
alert('hi');
$( '.ajax-live-on' ).removeClass('ajax-live-on');
});
I have used all the code to initialize the jquery no problem , all right. But this piece of code not working
Here is the jsBin link
http://jsbin.com/doxeravizo/1/edit?html,css,js,output
The $('.ajax-close') collection doesn't contain the elements taking that class after the binding.
Change
$('.ajax-close').click(function( event ){
to
$(document.body).on('click', '.ajax-close', function( event ){
You should also move that binding outside of the loop, there's no reason to do it at every iteration.
Note also that in order to have your span clickable, it must have some content.
Demonstration (I added the jQuery library to make the fiddle work)
I'm guessing that because you're using ajax, your .ajax-close is not created when the event listener is being created.
You're going to want to delegate your click function:
$(document).on('click', '.ajax-close', function(event) {
event.preventDefault();
alert('hi');
$('.ajax-live-on').removeClass('ajax-live-on');
});
This article will help, but just for reference, this bit in particular:
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.
One option is to listen on the click event using a delegate, like so:
$(document).on('click', '.ajax-close', function( event ){
//your code
});
Another option might be to move your click listener inside the original click listener, which creates the "Close" button, while the reason the issue arises is that the click event on "ajax-close" is bound too soon (before the <span> is appended to the DOM even):
ajaxcontent.click(function(event) {
event.preventDefault();
$( '.ajax-live' ).addClass('ajax-live-on');
$( this ).after('<span class="ajax-close animated bounceInRight">Close</span>');
$('.ajaxshow').append().load(ajaxUrl);
$('.ajaxshow').addClass('animated bounceInUp');
// Move this section here, which was previously located below
$('.ajax-close').click(function( event ){
event.preventDefault();
alert('hi');
$( '.ajax-live' ).removeClass('ajax-live-on');
});
});
Make sure to include some content in your "ajax-close" span to be able to click it like the word "Close".
Add JQuery library to your HTML head :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
In your given link you are adding element dynamically, so need to use event delegate for dynamically created elements event binding.
$(document).on('click', '.ajax-close', function( event ){
//your code
});

Loaded content can not call parent's function

I have a document with:
<button class="route" data-route-url="/about">About</button>
About
<div id="page-content">
</div>
$('.route').click(function() {
console.log('.route.click()');
var url = $(this).data('route-url');
$('#page-content').html('loading...');
$.get(url, function(data) { $('#page-content').html(data); });
return false;
});
It works perfectly until this point, and loads the about page.
The about page bring another button that also calls "route":
<button class="route" data-route-url="/contact">Contact</button>
But, when I click on it nothing happens, and I also dont get the console.log message, so seems that the page, that was first loaded inside the div-content can not see the parent function called route, is this working as expected?
How am I supposed to make this work?
You can do this by using Event Delegation with .on() since your button is added dynamically to DOM, The event registered before doesnot apply to the newly added button. SO you need to go with Event delegation, i.e attach the event to the parent container (which exists already) or document element(as i have used in the code) and set up for delegation once an element with the class '.route' is available anytime now or in future.
$(document).on('click','.route' ,function() {
console.log('.route.click()');
var url = $(this).data('route-url');
$('#page-content').html('loading...');
$.get(url, function(data) { $('#page-content').html(data); });
return false;
});
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.

jquery script doesn't work after using .html()

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
}

jQuery on() event only working with $(document)

I'm using jQuery's .on() event handler and it's only working when I use $(document).
This works:
$(function() {
$(document).on("click", ".search .remove", function(e) {
console.log("clicked");
});
});
This does not work:
$(function() {
$(".search .remove").on("click", function(e) {
console.log("clicked");
});
});
Nothing happens on that second one...no errors or anything. It just doesn't fire.
You are using two different syntaxes of .on which have two very different outcomes.
Your first is:
$(context).on("event","targetselector",handler)
This binds the event to context, and any events of type event that gets to the context that has an e.target that can be selected with targetselector will trigger the handler with e.target as the context. this is commonly known as event delegation.
Your second syntax is
$(targetselector).on("event",handler)
In this case, the event is bound directly to the elements currently on the page that match targetselector, not future elements. This is essentially the same as the old .bind.
Your second example doesn't work because your elements are created dynamically. When using .on() with dynamically inserted elements, you have to bind it via an element that isn't inserted dynamically, i.e. one that exists on the page at load time.
You can continue to use document as an ancestor element but in terms of performance you might want to find an element closer in the DOM to ".search .remove".
From the jQuery docs on .on():
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().
To ensure the elements are present and can be selected, perform event
binding inside a document ready handler for elements that are in the
HTML markup on the page. If new HTML is being injected into the page,
select the elements and attach event handlers after the new HTML is
placed into the page. Or, use delegated events to attach an event
handler, as described next.
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.
Your first method is the on() equivalent for the deprecated method live(). Probably your elements get inserted dynamically after the page loading has finished.
You could rewrite your code like following and it should work:
$(function() {
$(".search").on("click", ".remove", function(e) {
console.log("clicked");
});
});

Categories