My question is similar to others, but as the answers vary so much depending on how the code is first setup, I still haven't found a suitable answer to my question. Let me take you through the steps I take to try to run my JavaScript.
I open a new tab in my browser, press "Ctrl + O" to bring up the file explorer, then open the html file that links to the JavaScript. The code just never executes from the file; it'll only run if I run it from Scratchpad.
How do I get my JavaScript to run from the "script.js" file without having to copy it into Scratchpad?
function autocomplete(inp) {
if (inp) {
/*execute a function when someone writes in the text field:*/
inp.addEventListener("input", function(e) {
console.log("We have input! - " + inp.value);
});
/*execute a function presses a key on the keyboard:*/
inp.addEventListener("keydown", function(e) {
console.log("We have keydown! - " + e.keyCode);
});
}
}
// Run autocomplete when there is imput
autocomplete(document.getElementById("myInput"));
<head>
<link rel="stylesheet" href="styles.css">
<script src="script.js" type="text/javascript"></script>
<title>Autocomplete Test</title>
</head>
<body>
<div>
<div>
<h2>Input Tester</h2>
<p>Enter text into the field to test</p>
<form class="autocomplete" autocomplete="off">
<div class="wrapper">
<input id="myInput" type="text" name="myCountry" placeholder=" Search Hotels">
<!-- Trigger/Open The Modal -->
<button type="button">Search</button>
</div>
</form>
</div>
</div>
</body>
Note: This runs without issue on Stackoverflow. The error shows best when loading from a file you made (in a code editor of your choice), into your browser. I'm using the Atom code editor, in case anyone finds it relevant.
Script tags block by default; the browser waits for the script to finish executing before continuing to parse more HTML below it. So, at the time <script src="script.js"... runs, the document has not been populated yet.
Either:
(1) Give the script tag a defer attribute (preferred):
<script src="script.js" defer type="text/javascript"></script>
(2) Wrap the whole script in a DOMContentLoaded listener:
window.addEventListener('DOMContentLoaded', () => {
autocomplete(document.getElementById("myInput"));
});
(3) Move your script to the end of the body:
</div>
<script src="script.js" type="text/javascript"></script>
</body>
It is a better practice to place your link to JavaScript files just before closing the <body> tag so that You have your page loaded and then you can then get reference to it from your JavaScript.
Try this,
<head>
<link rel="stylesheet" href="styles.css">
<title>Autocomplete Test</title>
</head>
<body>
<div>
<div>
<h2>Input Tester</h2>
<p>Enter text into the field to test</p>
<form class="autocomplete" autocomplete="off">
<div class="wrapper">
<input id="myInput" type="text" name="myCountry" placeholder=" Search Hotels">
<!-- Trigger/Open The Modal -->
<button type="button">Search</button>
</div>
</form>
</div>
</div>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
Related
I just finished the W3 Schools certification course on JavaScript.
Can somebody explain why the returnValue() function works for the inField element, but not for the output element.
I'm guessing I have to create a variable and then reference the variable with the output element. Even if that is the solution I'd like to understand the logic behind this necessity.
Any assistance is appreciated.
HTML
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<div id='output'>Output: </div>
<div> Enter a value: <input type="text" id="inField"> </div>
<button onclick="returnValue()" id="submit">Submit</button>
</body>
</html>
JavaScript
function returnValue() {
document.getElementById("inField").value="Test";
document.getElementById("output").value="Test";
}
Very new to Javascript. I would like to pass a timestamp to a form when the user clicks a button, but I'm having trouble with getting the actual value to submit.
<html>
<head>
<script type="text/javascript">
var dateOfUser = new Date();
document.getElementById("userdate").value = dateOfUser;
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
// hide the content from user until they click the button
<script>
$(document).ready(function(){
$("#show").click(function(){
$("#ans").show();
});
});
</script>
</head>
<body>
<p>
Click the button to see the text.
</p>
<p><button type="button" id="show" onclick="userdate = new Date()">Show text</button></p>
<div id="ans" style="display:none">
<input type="hidden" id="userdate" name="timestamp" value="dateOfUser">
Here is the hidden text.
</div>
</body>
I've omitted the form submission code - unfortunately I did not write it and I don't have access to the code beyond using it for form submission.
But upon submission, the .csv file contains:
"timestamp":"dateOfUser"
And not the value of "userdate". As far as I understand, using document.getElementById("userdate").value = dateOfUser; should allow me to use "userdate" in the HTML.
Any help would be appreciated, I've poured over many similar questions on this site and others, but I am having trouble figuring out what I'm doing wrong.
you can remove the type="hidden" to test. At least it works for me using userdate.value.
<html>
<head>
</head>
<body>
<p>
Click the button to see the text.
</p>
<p><button type="button" id="show">Show text</button></p>
<div id="ans" style="display:none">
<input id="userdate" name="timestamp" value="dateOfUser">
Here is the hidden text.
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
// hide the content from user until they click the button
<script>
$(document).ready(function(){
$("#show").click(function(){
$("#ans").show();
$("#userdate")[0].value = new Date()
});
});
</script>
</body>
The way you put script above the body
<script type="text/javascript">
var dateOfUser = new Date();
document.getElementById("userdate").value = dateOfUser;
</script>
wouldn't work because the dom(i.e. the elements) has not loaded. While onclick and $(document).ready are different from the above way.
However, it's still better for you to put script at the bottom of body.
Dynamically adding a text input via AJAX and using the componentHandler.upgradeDom() works well.
However, when I clone a text input using JavaScript alone, that function doesn't help.
<html>
<head>
<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-amber.min.css">
</head>
<body>
<div id="formElements">
<div class="formElementGroup">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<label class="mdl-textfield__label" for="Q1">Question</label><input type="text" class="mdl-textfield__input" id="Q1" name="Q1[]">
</div>
</div>
<div id="Qs1"></div>
<div align="left">
<a id="Btn-addQuestion" class="Btn-addQuestion">
Add another text field
</a>
</div>
</div>
<script>
$(document).ready(function(){
$("#formElements").on("click", ".Btn-addQuestion", function(){
clonedTxtBox = $("#Q1").parents(".formElementGroup").clone(true);
clonedTxtBox.appendTo("#Qs1");
setTimeout(function(){
componentHandler.upgradeDom();
}, 1000);
});
});
</script>
</body>
</html>
I expect that the label of the cloned text input move upwards and become smaller as it is designed to behave. However, only the original one does-- the cloned one doesn't; it rather sticks over the text-input even if the user types something inside.
Any help would be appreciated.
JS Fiddle:
https://jsfiddle.net/jp26f0ts/
I found the solution somewhere online.
Before upgrading the DOM, I should have added this:
clonedTxtBox.find('.mdl-textfield').removeClass('is-upgraded').removeAttr('data-upgraded');
scripts.js
function homepageInput() {
var x = document.getElementById('homeForm').elements["whatdoyouwant"].value;
if(x.localeCompare("working") == 0){
document.location.href = 'new.html';
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="scripts.js"></script>
</head>
<body>
<div class= "boxContainer">
<div id = "box">
<form id="homeForm" onsubmit="homepageInput()">
<input type="password" name="whatdoyouwant" id="whatdoyouwant" placeholder="WTF..."/>
<input id="submit" type="submit"/>
</form>
</div>
</div>
</body>
</html>
when i type "working" into my password field it wont load the page new.html which is located in the same directory. Any ideas? When i use an alert in the same if statement it loads fine?
You trigger the function when you submit the form.
You do nothing to prevent the default behaviour of the form.
Consequently, you set location.href and then the form submission runs and you submit the form to the current URL.
The quick hack to solving this is to return false from your onsubmit function.
Modern code would bind the event handler with JavaScript and use preventDefault().
My HTML file:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" />
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<form name="someForm">
<input type="button" value="Click me" onClick="myFunction()" />
</form>
<div id="result"></div>
</body>
</html>
My script.js file:
function myFunction(){
$("#result").html("BUTTON WORKS");
}
I have Firebug, and whenever I click the button, Firebug throws me this error:
ReferenceError: myFunction is not defined
What am I doing wrong?
script can't be a self closing tag in HTML (it works on some browsers, depending on the doctype, but it's not correct). You must add a closing tag.
Replace
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" />
with
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
The script element pointing to your script probably isn't parsed correctly due to this error.
From the norm :
A script element must have both a start tag and an end tag.
Blockquote
Might be due to file reference issue.
It is a better practice to attach the event in the js file instead of HTML.
<form name="someForm">
<input type="button" id="btn" value="Click me" />
</form>
$('#btn').on('click', function(){
$("#result").html("BUTTON WORKS");
});
Do you open that file locally (you have file:// in address bar) or from some server (http:// protocol in address bar)? Because if you open file locally, you actually try to load jquery from address:
file://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
which is incorrect. It happens, because you use //ajax.googleapis.com/... as adress, which refers the same protocol as currently opened page.
Either change it to:
http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
of upload your file to some server (or even install one locally) and test it through full http request.
I solved the problem by combining answers from #Susbanth, #MBO, and #dystroy.
Here's my new HTML file:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<form name="someForm">
<input type="button" value="Click me" />
</form>
<div id="result"></div>
</body>
</html>
I added "http" to the jQuery source, closed the tag, and removed the 'onClick' from inside the HTML.
Here's the updated script.js file:
$(document).ready(function(){
$("input[type=button]").on("click",function(){
$("div#result").html("BUTTON WORK");
});
});
I made the onClick event a jQuery event.