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.