Running script after div added - javascript

Im using a plugin (Event Organiser Pro) that dynamically creates a div based on the input of a number field - basically it creates a duplicates the form fields depending on the number you enter in the input field.
I need to run some jQuery which is based on those form fields, but obviously cant run it until the div has been created.
How can i run the script once the div has been created? Is it possible to run script when div id has been created? Or something similar?

Yes, you can delegate the DOMNodeInserted event to the body.
function createDiv() {
$('<div />').addClass('test').appendTo($('body'));
}
$('body').on('DOMNodeInserted', '.test',function() {
alert('Created element .test');
})
$("button").on('click', function() {
createDiv();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Create</button>
In the example above the click on the button simulates your other script creating the div.
To rewrite the code to work with your setup you can strip the click part out and delegate the event listener to your id:
$('body').on('DOMNodeInserted', '#your_element',function() {
yourFunction();
// call a function here or add your code here directly
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note: This example won't work here because the element with that ID does not exist and neither does the yourFunction() function.

Related

How do I connect a textbox to jquery events dynamically?

I have an application that uses jquery when editing date fields. It works on all fields that have the css class "date". I am reading some HTML code from the server into a DIV that functions as a pop up window. The HTML code includes several date fields and I want to have jquery manage those fields, too. The page has code pasted below in the head element and jquery automatically attaches to the appropriate fields. I need to add fields to jquery when the pop up appears and remove them when the pop up closes. When searching for an answer I could only find where jquery creates a textbox, but not attach to an existent textbox.
<script src="Include/jquery-latest.js" type="text/javascript"></script>
<script src="Include/jquery.maskedinput.js" type="text/javascript"></script>
<script type='text/javascript'>
$(function () {
// Define your mask (using 9 to denote any digit)
$('.phone').mask('(999)999-9999');
});
$(document).ready(function () {
$('.phone').change(function () {
var validnum = $(this).val().match(/^([01]?[0-9]|[0-9]|[0-9])[0-9]|[0-9]|[0-9]-[0-9]|[0-9]|[0-9]|[0-9]$/);
if (!validnum) {
$(this).val('').focus().css('background', '#fdd');
alert('Please enter a valid Phone Number (999)999-9999.');
} else {
$(this).css('background', 'transparent');
}
});
});
$(function () {
// Define your mask (using 9 to denote any digit)
$('.date').mask('99/99/9999');
});
$(document).ready(function () {
$('.date').change(function () {
var validnum = $(this).val().match(/^(0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])[\/\-]\d{4}$/);
if (!validnum) {
$(this).val('').focus().css('background', '#fdd');
alert('Please enter a valid Date mm/dd/yyyy.');
} else {
$(this).css('background', 'transparent');
}
});
});
</script>
Why doesn't your solution work?
By using $('.date').change(... jQuery attaches event listeners to all elements present in the DOM the moment you execute this function. As your modal gets added in later, it won't have received a listener.
Solution: $(document).on('change', '.date', function () { ...
By using this, you attach the event listener to the document root, so every time anything in the document changes, jQuery checks, if the changed element matches the selector you've provided as the second param (in this case .date). So all elements, even those added later to the page will react to changes.
BUT: As I said, you attach a listener to the document. As jQuery uses a shadow-DOM in the background it won't cost you much performance, but if you build a big application with many of these listeners, you might run into performance issues at some point. In this case you'd better add the listeners specifically to the element you just added.
Since the mask and event functions are enclosed, I moved them to the routine that creates the pop up and that resolves the issue, causing them to be called again each time. I placed a date test textbox on the form and displayed properties. Each time there was only one jquery property present, so it appears everything was removed and rewritten each time.

jQuery's .on('click') not working

Templating is done in Jade, #name is putting a ID on the tag and .name puts a class
div#chatroom
div.row#chatcontainer.chatbg
div.large-12.columns
div.row
div.large-10.columns
h2#chatanchor.thin Party
i.fa.fa-minus-square-o
div.large-2.columns
i.fa.fa-users
div.row.chatbox
div.large-12.columns.chatwindow
div.mymessage
p Bill: Templating!
div.theirmessage
p.theirmessage Fredrickson: Templating!
div.row
div.large-12.columns.sitbottom
div.row.collapse
div.small-10.columns.large-10.sitbottom
input(type="text").sitbottom
div.small-2.columns.large-2.sitbottom
button(type="submit", class="button postfix sitbottom") Send
I have a simple chat window and when I click the h2 at the top it is supposed to minimize using this:
$('#chatanchor').on('click', function(e) {
console.log("Here");
});
The bind is called within document.ready in jQuery but doesn't work when I click it, but if I copy the code and paste it into the dev console and then click it, it works, so I'm not sure why it is not binding on page load.
It would seem that the element is being added after the DOM is ready, so your event isn't getting attached. Have it attach to any new elements that match your selector with the following:
$(document).on('click', '#chatanchor', function(e) {
console.log("Here");
});

Loading several .php file into one div

Hello i have this code to load php file into div. Its working but i need load next file into this div.
<script type="text/javascript">
$(function() {
$("a.load").on("click", function(load) {
load.preventDefault();
$("#zaw").hide().load(this.href).fadeToggle(1000);
});
});
</script>
<li><a class="load" href="zzz.php">zzz</a></li>
If i click "zzz" link loading file into my div (file table with images) i need hide this page and load next by click image.
UPDATE
Now working
<script type="text/javascript">
$(function() {
$("a.load").on("click", function(load) {
load.preventDefault();
$("#zaw").hide().empty().load(this.href).fadeToggle(1000);
});
});
</script>
You just simply need to bind another click event to an image (or table body) that you load through load() function. However, you may experience some issue with your click not working, and heres why:
If you attach two click handlers, one for a.load and second for, let's say, .image than only the first event will actually get bind to its element, and the socond one won't be attached because, well, .image doesn't exist yet - not untill you load it.
You could expect, that once you php file content will get loaded (with .image elements in it), then clicking them will fire an action you have declared, but it won't - those .image's are new DOM elements and they missed an event binding procedure which was done only once when the DOM was created (or DOM was ready if you use $.(document).ready()).
So, in order to get those clicks to work you need to either attatch them on load() function callback, like so:
$("a.load").on("click", function(load) {
load.preventDefault();
$("#zaw").hide().load(this.href, function(){
$(".image").on("click", function(e) {
$("#zaw").hide().load(/* load what you want */);
});
})
.fadeToggle(1000);
});
or insert .image click event binding inside php file you are loading or use some sort of delegation, for example:
$(document).on('click', '.image', function(){
/* do what you want */
});
which will make sure that even new, dynamically created DOM element will fire an action you want.

Simple javascript to update a textbox when a button is hit?

I have a simple form that I'm playing around with and I'm trying to update a textbox value when a command button is clicked. The command button is called btnVerifyLocation and the textbox is called txtGeoLocation. I've attempted to do this in Javascript with the following:
The code I have is as follows:
<script type="text/javascript" id="testing">
$("btnVerifyLocation").click(function ()
{
$("input[name*='txtGeoLocation']").val("testing");
});
</script>
However when I click the button nothing happens.
A) You're missing a # in 'btnVerifyLocation' (I'm assuming that's its ID, otherwise if it's a class then use '.btnVerifyLocation'
B) Second, this should be in a $(document).ready(), otherwise you are trying to bind a click handler to a DOM element that hasn't yet been rendered.
Code should be as follows:
$(document).ready(function() {
$('#btnVerifyLocation').click(function(e) {
e.preventDefault(); // In case this is in a form, don't submit the form
// The * says "look for an input with a name LIKE txtGeoLocation,
// not sure if you want that or not
$('input[name*="txtGeoLocation"]').val('testing');
});
});
jQuery’s selector function uses CSS selector syntax, so to identify an object with an ID, you need to prefix the ID with a #:
$("#btnVerifyLocation").click(function () {
$("input[name*='txtGeoLocation']").val("testing");
});
Also just in case: You do have jQuery included, right?

bootstrap typeahead selector for dynamic page loading

When I load a page normally and use this code :
$('#clientName').typeahead({
//removed options since they are not needed for my question
});
The typeahead works fine on #clientName.
But when I load the input #clientName dynamically via AJAX then the above code doesn't work.
Is there some way to let it work?
It's equal to this problem :
$('#randomDiv').click(function() {
alert("Handler for .click() called.");
});
This one only works if the content is not dynamically loaded. But this code will work :
$(document).on('click','#randomDiv',function() {
alert("Handler for .click() called.");
});
So I would like to add the handler to the document or body, and not to the #clientName div itself.
I think you only have the choice to call $('#clientName').typeahead(...); again after inserting the input with the id clientName dynamically. If you capsules calling typehead into a function, you need only to call the function again without setting all options again.

Categories

Resources