I'm trying to check if the input is empty with jQuery and the code doesn't work.
That's the code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="demo.js"></script>
</head>
<body>
<form>
<input type="text" id="name">
<input type="submit" id="btnConnect">
</form>
</body>
</html>
$('#btnConnect').click(function()
{
if($('#name').val() == '')
{
alert('Input is empty!');
}
});
Your problem has two easy solutions.
Basically, you call your script before the rest of the page loads. Your script tries to attach to #btnConnect, which doesn't exist yet.
1). Use document.ready or window.onload. The script will only execute after the whole page loads, so it should work as you meant it to.
2). Place the JS files at the bottom of the document, right before the closing body tag. Most programmers chose to put the scripts at the bottom of the page, because if you have large scripts, the user sees a blank page untill they load.
It works quite well, because most of the time JS is not required until the user begins interacting with the site. It also enables progressive rendering.
For more good JS practices, check out:
JSTheRightWay.org
Hope this helps!
Related
I am trying to teach myself how to modify the DOM using JavaScript. I am at a loss about the following.
This is an HTML snippet.
<html>
<body>
<h1>A heading</h1>
<div id="myDIV"></div>
<script type="text/javascript" src="thejs.js"></script>
<script type="text/javascript">
document.getElementById("myDIV").innerHTML="<p>Try this one comes from script inside html source</p>"
</script>
</body>
</html>
I expect to get a similar result from the external js file linked in the script, which contains this:
document.getElementById("myDIV").innerHTML="<p>While this one comes from a separate JS file</p>";
But nothing happens... I realise this is probably silly, I apologize.
The first script runs and sets the content of the div to "While this one comes from a separate…"
Then, after some time which is imperceptible to a human, passes the second script runs and sets the content of the div to "Try this one comes from script…".
If you want both paragraphs to appear you need to append (e.g. with +=) the data instead of replacing it.
That said, appending chunks of HTML with innerHTML += can cause some issues (it's inefficient as that whole chuck of DOM has to be regenerated and it will blow away inline event handlers) so you are usually better off using the insertAdjacentHTML method instead.
The output depends on where you have included the external js. If you have included it before your embedded script, it will not have any effect, as eventually, it will be overridden by your embedded script. However, if you include the external js after your embedded js, it will work as you want to.
<html>
<body>
<h1>A heading</h1>
<div id="myDIV"></div>
<script type="text/javascript" src="thejs.js"></script>
<script type="text/javascript">
document.getElementById("myDIV").innerHTML="<p>Try this one comes from script inside html source</p>"
</script>
<script type="text/javascript" src="external.js"></script>
</body>
</html>
I have following HTML,
$(document).ready(function() {
$('#searchMovieBtn').click(function(e) {
e.preventDefault();
console.log('search');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="searchMovieBtnBox">
<button class="btn btn-primary" type="button" id="searchMovieBtn">Search</button>
</div>
When I click on button, nothing happens, it seems like event is not triggering.
It is a caching issue. When you was developing and testing your JQuery code, your old code remained into the browser cache. Browser cached it to load page faster in next uses. In order to solve this problem you have 3 options.
Delete your browser history
Refresh your browser by pressing Ctrl + F5 (Preferred for developing purpose)
Tell browser that this JQuery code has changed by adding a version for it. It is used when you are publishing your code on the server because you can't ask your clients to delete their browser history or load your page by pressing Ctrl + F5
Here is how you could add version to your JQuery code:
<script type="text/javascript" src="js/script.js?v=1"></script>
Look at v=1. Next time when you updated your JQuery code change it to v=2 to tell browser that your code has been changed.
You can try the next thing,
First of all, your HTML markup I think it might be wrong as you are not pointing out correctly the folders.
I attached all the css and js bootstrap + jquery files through a CDN.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"</script>
<script type="text/javascript" src="js/script.js"></script>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<title> jQuery button click event working?</title>
</head>
<body>
<div id="searchMovieBtnBox">
<button class="btn btn-primary" type="button" id="searchMovieBtn">Search</button>
</div>
</body>
</html>
Therefore,your script.js stays as it is.
For me it has worked like this. I got the message printed onto my console.
Hope that helps you.
Make sure you don't have another element in the HTML with the same id.
I have read that if you want to make it look like your site loads faster then you should put your javascript at the end of your html file like the following
<html>
<body>
</body>
<script>
//my awesome javascript functions go here because it lets things load faster
//than if it was at the top
</script>
</html>
The problem is when I create buttons or use onChange events that call these functions.
How am I meant to keep my JS at the bottom of the page and have the JS defined for when it reads that the js function will need to be called?
For example
<html>
<body>
<input type="text" onChange="myfunction()"/>
</body>
<script>
function myfunction(){}
</script>
</html>
I did the code in pseudo code-ishly so you wouldn't focus on any of my syntax errors, but more focus on how I am meant to go about this.
When creating the page, it creates the html properly, but gives me a console error saying "myfunction" is not defined.
If I move the script part above the body this works, but it is recommended to keep it last to increase speed in page load.
Just a note I am not using jquery.
I originally thought this was a duplicate (Javascript at the bottom, function call in the body?) but it doesn't seem to answer my problem.
------------------------update----------------------------
using event listeners
<html>
<body>
<input type="text" id="myawesometext"/>
</body>
<script>
function myfunction(){}
element = document.getElementById('myawesometext');
element.addEventListener("onChange", myfunction, false);
</script>
</html>
I've been trying to create this chrome extension that you enter an address and click a button and it goes there. This may sound like a stupid idea but somehow a server block on a site is bypassed by chrome extensions. This is my current code:
<html>
<head>
<title>Website Opener</title>
<style type="text/css">
body
{
font-family: "Lucida Grande";
height: 100%;
}
</style>
<script>
$(document).ready(function() {
$('#url').change(function() {
var newurl = $('#url').val();
$('a.target').attr('href', newurl);
});
});
</script>
</head>
<body>
<form>
<input type="text" id='url' value='http://'>
<br>
<p><a class="target" href="">Go!</a></p>
</form>
</body>
</html>
What it currently does is just make the page blank or clear the input box instead of going to the new site.
I have tried javascript .open() method, this is trying jQuery. I'm mainly wondering if there are any other ways to do this or if I'm missing something.
This will help you:
Place jQuery to your <head> or in the end of your page, but before your code.
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
Then rewrite your code to use a keypress event:
$(document).ready(function() {
$('#url').keypress(function() {
$('.target').attr('href', this.value)
})
});
FYI: change event will happen when you changed a value of your input and set the focus out of it. So if you type an url and place your mouse cursor on the link and press it, change event will trigger AFTER your click. So be careful with those events.
UPDATE:
I just saw that you're doing an extension for GC.
The best practices tell us to divide application by layers' aim. HTML and JS should be separated.
In your manifest.json you have to add
"js": ["jquery.js", "content_script.js"]
and move your JavaScript logic from HTML file to the content_script.js.
<html>
<head>
<script>
if(document.readystate == "interactive"){
alert(document.forms[0].method);
}
</script>
</head>
<body>
<form name="form1" id="form1" method="post">
</form>
<input type="submit" id="submit" name="check" onclick="check()">
</body>
</html>
I also wrote alert() box within the function and triggered with the submit button, in that case the it executed but why isn't it executing in this stage.
First off, there are a several logic/design errors:
It is document.readyState (different capitalization).
While parsing the <head> section, your document will NEVER have document.readyState == "interactive" because the document doesn't switch to that state until it is done parsing the <body>, but by definition it is only parsing the <head> section at this moment.
If you thought your code would somehow fire when the readyState became == "interactive", then that's just not how a simple if statement works. It tests that condition at the moment the code runs and if it's falsey which it is here, then it will never execute.
If you want to run code when the document is loaded and the DOM is ready to modify and interact with, you can see a summary of your options in this answer.
Your options boil down to this:
Move your javascript to a script tag right before the </body> tag and remove the if test you have. At that point in the document parsing, it is safe to interact with any DOM element that was defined before the script.
In modern browsers, add an event listener for the DOMContentLoaded event and run your code when that event fires.
For more general support including older browsers, get a more complete implementation of a function that will notify you when the browser is safe to interact with. You can see such an implementation that works in pretty much all browsers in use today in this other answer.
Use some sort of javascript framework that already offers you a cross browser way to know when the DOM is ready. jQuery offers $(document).ready() as do pretty much all other similar frameworks.
This simplest solution to your code would be this:
<html>
<head>
</head>
<body>
<form name="form1" id="form1" method="post">
<input type="submit" id="submit" name="check" onclick="check()">
</form>
<script>
alert(document.getElementById("form1").method);
</script>
</body>
</html>
Working demo: http://jsfiddle.net/jfriend00/Ka4rL/
P.S. I presume you want your <input> tag inside the form. And, I'd recommend you change to using document.getElementById("form1") rather than forms[0] as this is a much more robust way to program because your code doesn't break if someone adds a new form to the page.