jQuery document.ready() not firing for dynamically loaded content - javascript

I've got a PHP file (called aboutMe.php) that contains some HTML as follows:
<script type="text/javascript" src="/aboutMe.js"></script>
<div id="aboutme-gender" class="aboutme-block">
<div class="aboutme-question">My gender is:</div>
<div class="aboutme-error">Please select your gender.</div>
<div class="aboutme-answer">
<input id="gender-male" name="the-gender" type="radio" value="1" />
<label for="gender-male">Male</label>
<input id="gender-female" name="the-gender" type="radio" value="2" />
<label for="gender-female">Female</label>
</div>
</div>
The aboutme.js file contains a function as follows:
jQuery(document).ready(function($) {.....does stuff to the tags in the HTML});
This all works fine if the page is loaded directly. However when another page wants to load this dynamically as follows:
$("#load-aboutme-here").load("aboutMe.php");
...the document.ready() event doesn't fire and things don't get tagged.
I've seen similar posts but can't quite get what I need from them. Have done things like substitute the document.ready() for window.load() but then it doesn't even work at all when the aboutMe.php page is loaded directly.
Any ideas much appreciated - this is driving me nuts although I suspect it's an easy fix!
Thanks
Iain

Note that the document is the main page...not subsequent files you retrieve
The document was ready long before the ajax is done so any $(document).ready() that is called after it is ready will fire immediately. In your case it will fire before the elements exist
Move the script tag below the html that the code is referencing
<div id="aboutme-gender" class="aboutme-block">
.......
</div>
<script type="text/javascript" src="/aboutMe.js"></script>

If I understood your problem correctly, I believe you could just create a callback for the .load() function like so:
$("#load-aboutme-here").load("aboutMe.php", null, function()
{
// Code to be executed when aboutMe.php is loaded.
// i.e. The code in aboutMe.js
});

Related

jquery - event handler works if pasted into Console but not when included through .js file

I have an application using jquery 3.2.1
One of the pages contains 2 <form> elements which have the same class name, .products-ctp__search-form. The HTML for this is rendered on page load:
<form class="products-ctp__search-form">
<input name="n1" type="text">
</form>
<form class="products-ctp__search-form">
<input name="n2" type="text">
</form>
I want to target the <input> elements in each form and use an event handler to deal with the user entering input into either of them. So I've written this inside a foo.js file and then linked it at the bottom of the page:
<!-- Form markup above is here -->
<script src="foo.js"></script>
The foo.js file contains:
$(function() {
$('.products-ctp__search-form input[type="text"]').bind("keyup change input",
function (e) {
console.log('debug');
console.log(e);
});
});
When I enter text into either input it doesn't log anything to the console.
But if I paste the script above into my console, it will, e.g.
debug
VM726:4 r.Event {originalEvent: InputEvent, type: "input", target: input#n1.form-control.form-control.input-border-secondary, currentTarget: input#n1.form-control.form-control.input-border-secondary, isDefaultPrevented: ƒ, …}
Strangely if I get rid of 1 of the inputs (e.g. removing the form containing n2 and keeping n1) it works fine. Other pages in the application have just 1 input and the equivalent code - when included from a linked .js file - works fine.
So I've read jquery works in console, but not in linked js file but this seems to suggest waiting for something to load. In this case the markup is rendered on page load (not via ajax, etc) and the jquery code is inside document.ready.
There is another post jQuery works in console but not in .js file which I read but again this seems to suggest having to wait for something to load. If this is the case then what am I supposed to wait for and how to I bind this?
The linked posts make sense when you're waiting for something like an image to load. But how does this work if it's just the markup of the page? Or is that not actually the problem?
jquery is included in the <head> of the document whereas the foo.js file is inside <body>. So I don't believe it's an issue of foo.js being included before jquery, etc.
I have tried your code and found that console.log(e) is causing issue (not sure why it is throwing error in console). Comment this part and don't use bind, use 'on' as bind is deprecated in jquery.
$(function() {
$(document).on("keyup change input", '.products-ctp__search-form input[type="text"]', function (e) {
console.log('debug');
//console.log(e);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<form class="products-ctp__search-form">
<input name="n1" type="text">
</form>
<form class="products-ctp__search-form">
<input name="n2" type="text">
</form>

Radio button click event is not getting fired

This may seem to be duplicate question as people already asked such question and I read the answers too. But still this is not working for me. When I click on radio button, nothing happens. Below is my HTML code:
<div id="bank-details" class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<input type="radio" id="bank" name="pmt-method-radio" value="ACCOUNT" checked="checked">
<label for="bank">Checking Or Savings Account </label>
<input type="radio" id="card" name="pmt-method-radio" value="CARD">
<label for="card">Credit/Debit Card</label>
</div>
</div>
And below is my jquery code:
$('input[type="radio"]').click(function(){
alert("fired");
alert($("input[name=pmt-method-radio]:checked").val());
});
Use jquery when document ready
$( document ).ready(function() {
$('input[type="radio"]').click(function(){
alert("fired");
alert($("input[name=pmt-method-radio]:checked").val());
});
});
The ready event occurs when the DOM (document object model) has been
loaded. Because this event occurs after the document is ready, it is a
good place to have all other jQuery events and functions. Like in the
example above. The ready() method specifies what happens when a ready
event occurs.
Here is the working piece with your code only without any changes
https://jsfiddle.net/zooym4ow/
Common mistakes one usually make.
Either jquery library is not included or it's not included before the mentioned code.
Radio button was not loaded in browser when the code was getting executed. This happens if the code was included within <head> tag.
To handle this, either wrap your code within document.ready event handler as mentioned by #AmanRawat or put all of your code at the end in <body> as shown below.
$(document).ready(function(){
//Your code goes here
});
OR
<body>
<!-- Your DOM elements here -->
<script>
//Your code goes here
</script>
</body>

Loading External JavaScript file after view page is loaded in AngularJs

<div ng-app>
<form ng-submit="addTodo()">
<input type="text" ng-model="todoText" size="30"
placeholder="add new todo here" id="inputtext">
<input class="btn-primary" type="submit" value="add">
</form>
<script type="text/javascript" src="js/process1/Process1Controller.js"></script>
I want to load specified js file after html load since id of input textbox is used in js .
i have seen different thread and done many experiments for this like
$scope.$on('$viewContentLoaded', function(){
})
but issue not resolved
This is a hack, and not likely the proper way to do things, but try using ng-if to dynamically populate the items on the page:
//HTML
<script ng-init='myVariable = true' ng-if='myVariable' type="text/javascript" src="myJsToLoad.js"></script>
again, this is not the proper way to do things in angular, but it should work
As per my suggestion,
put the entire js code in a function, like below:
function loadmyjs(){
// put your entire related js code here...
}
And inside the current controller, call that js method like, When your id is created....
loadmyjs();

Why the onload focus doesn't work on this script?

This is a sample of my form. when the page loads the focus must be on 'fbox' but it dosent work and i don understand why. the form contains a niceditor but i dont think that is the problem
<html>
<head></head>
<body onload="document.form.fbox.focus();">
<body>
<form method='post' action='' name='form' >
Headline <input name='fbox' type='text' class='form' id='box' autocomplete='off' size='80'><br>
Your text</font><br><script type="text/javascript" src="nicEdit.js"></script><script type="text/javascript">bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });</script>
<textarea name="description" style="width: 100%; height:200px;"></textarea></p>
<p><select name='catg' >
<option value='' selected >Select category</option>
</select>
<input type="submit" id='button' name="Submit" value="Submit" class="button"></form>
</body></html>
thanks
You've got two body tags. I suggest getting rid of one of them and seeing if that helps.
There's also a stray closing </font> tag in the middle of that code. Many people try to arrange their markup so that it's easy to read and to see the structure of the document. You might want to explore that practice.
Another possibility is that your "nicEdit" plugin is un-doing the ".focus()" call. Try taking that out and seeing if the focus works (as an experiment). If that's happening, then you can do your "focus()" call after the nicEdit code has finished:
bkLib.onDomLoaded(function() {
nicEditors.allTextAreas();
document.form.fbox.focus();
});
(That's an adaptation of the code in your existing <script> block.)
You have two body elements. That won't work.
Scripts run top-to-bottom, so you're firing the "onload" before the rest of the page has rendered. It's likely the element you are trying to focus is not there when the event fires.
There are a number of ways to fix this. jQuery has a handy method that waits until the DOM is ready.
A simple way is simply to run your script from the bottom of the page in a script block.
<script type="text/javascript">
document.form.fbox.focus()
</script>

Nicest way to run some JS immediately after an element has loaded?

Let's say you've got some HTML,
<input id="mytextbox" type="text" value="hello world" />
And you want to do some magic on that textbox as soon as it's loaded. Maybe add some kind of widget, or button beside it, whatever. There's 2 ways of doing this that I'm aware of. You can throw some jQuery like this in the <head>
$(function() {
$('#mytextbox').magic();
});
And that'll run once the entire DOM is ready, but what if we want it sooner? As soon the element has loaded?
We can put the JS immediately after the element:
<input id="mytextbox" type="text" value="hello world" />
<script>
$('#mytextbox').magic();
</script>
But that's a bit messier, and why should we have to search the entire DOM for an element ID when we know exactly where it is? onclick events have a this argument. Isn't there some way we can do something like this...
<input id="mytextbox" type="text" value="hello world" onload="$(this).magic()" />
? Would be nicest solution IMO, but only the body has an onload event apparently, and no other event seems suitable. Are we basically left to solution #2 if we want some piece of code to run immediately after an element is loaded?
Actually, your second snippet is the "best" (whatever that means, probably fastest) way to apply some Javascript to an element.
<input id="mytextbox" type="text" value="hello world" />
<script type="text/html">
$('#mytextbox').magic();
</script>
You are not searching the entire DOM here. A call like this directly goes down to
document.getElementById('mytextbox');
which is more or less, just insta-access to the node.
Anyway, a practice like this betrays the idea of unobtrusive Javascript. I wouldn't know a reason why you shouldn't apply some code when the DOMContentLoaded event fires (which is abstracted away by jQuerys .ready()).
Since javascript includes are generally blocking (unless you load it async ofcourse), it is always a good idea to put your javascript as low as possible on the page. That way the user won't have to wait for your javascript to load while browsing through the page.
So the question here is, do you really want it to load immediately after that element. Or simply at the bottom of the page.

Categories

Resources