This question already has answers here:
Why does this simple JSFiddle not work? [duplicate]
(8 answers)
Closed 3 years ago.
I am beginner to JS and receiving error on this code.
I could not make it work and getting this error:
calc is not defined at HTMLButtonElement.onclick
Searching different stackoverflow questions and other sources online
<form>
Value 1: <input type="text" id="value1"> Value 2: <input type="text" id="value2">
<br/> Operator:
<select id="operator">
<option value="add">Add</option>
</select>
<button type="button" onclick="calc()">Calculate</button>
</form>
<input type="text" id="result"/>
JS Code:
function calc(){
var n1 = parseInt(document.getElementById('value1').value);
var v2 = parseInt(document.getElementById('value2').value);
var op = document.getElementById('operator').value;
if(op === 'add'){
document.getElementById('result').value = n1+n2;
}
I am getting the error I shared above in console.
JSFiddle
You're getting that error because the calc function is not defined when the HTML is rendered, therefore the onclick instruction can't point to it. Later on, when the user clicks on the button, the JavaScript engine notices that you're trying to execute an undefined function and throws an error.
You can solve this by registering the event listener after you define the function in your script, for example with this line (though things would be much better if the button also had an id):
document.getElementsByTagName("button")[0].addEventListener("click", calc);
For reference, see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
Related
This question already has answers here:
Using HTML script tags to code while they have a source
(2 answers)
Closed 2 years ago.
This is a Django (python) developer trying to do some frontend stuff for the first time.
Frontend script
<script language="JavaScript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
function dropdownFunc(val){
console.log(val.includes("NoneOfThese_"))
if (val.includes("NoneOfThese_")) {
$("#dropdown-list_" + val).show();
}
else {
$("#dropdown-list_" + val).hide();
}
}
</script>
dropdown-list div:
<div id = "dropdown-list_{{phone_array.count}}" class="jumbotron" style="display:none">
<form method="POST" action="{% url 'insertPhoneDetails' %}">
<label for="brandName">Brand name:</label><br>
<input type="text" id="brandName" name="brandName"><br>
<label for="mobileName">Mobile name:</label><br>
<input type="text" id="mobileName" name="mobileName"><br>
</form>
</div>
Error on line 32: <input type="radio" name="options" value="{{key}}" id="dropdown" onclick="dropdownFunc(value)" required> {{value}} <br><br>
Error:
Uncaught ReferenceError: dropdownFunc is not defined
at HTMLInputElement.onclick ((index):32)
How to tackle this?
You can't have a single script tag that both has a src and contains inline text. Separate them out into two separate script tags instead:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function dropdownFunc(val){
// ...
</script>
But you also aren't passing the value to dropdownFunc correctly, and you should also consider avoiding inline handlers, since they have horrible scoping rules and escaping issues. Attach the event listener properly using JavaScript instead, eg:
$('#dropdown').on('click', e => dropdownFunc(e.target.value));
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 4 years ago.
A simple form to submit search result
<form>
<label for="searchTerm">Search Term</label>
<input type="text" id="searchTerm" name="searchTerm">
<button type="submit">Search</button>
</form>
in main.js
const form = document.querySelector("form");
const input = document.querySelector("input");
//adding listener to form
form.addEventListener("submit", formSubmitted);
I am getting two errors ?
Uncaught TypeError: Cannot read property 'addEventListener' of null
Uncaught SyntaxError: Identifier 'form' has already been declared
Silly mistake : i had imported same main file twice in same file
<script src="main.js"></script>
With document.querySelector() it is best to use an element id #someId or a class specifier .someClass, or even a combination of both. See MDN Reference.
As for why it complains about form: it apparantly is defined already elsewhere, just pick a more unique name, or wrap your code in a function and then call that function.
const form = document.querySelector("#theForm");
console.log("form: " + form);
const input = document.querySelector("#searchTerm");
form.addEventListener("submit", formSubmitted);
function formSubmitted() {
//...
}
<form id="theForm">
<label for="searchTerm">Search Term</label>
<input type="text" id="searchTerm" name="searchTerm">
<button type="submit">Search</button>
</form>
This question already has answers here:
Why this JSFiddle does not work [duplicate]
(1 answer)
jsFiddle: no connection between html and js? Can't call simple function from button? [duplicate]
(1 answer)
Closed 5 years ago.
ive used a basic example from w3schools.com to get here:
https://jsfiddle.net/02wu0v49/
function myFunction() {
var x = document.getElementById("fname").value;
document.getElementById("demo").innerHTML = "aaaaaa";
document.getElementById("fname").value = "bbbbb";
alert("lala3");
}
<body>
<p>A function is triggered when the user releases a key in the input field. The function outputs the actual key/letter that was released inside the text field.</p>
Enter your name: <input type="text" id="fname" onkeyup="myFunction()">
<p>My name is: <span id="demo"></span></p>
</body>
somehow the w3schools version works but it wont do anything on jsfiddle?
and it would be really nice to use [code][/code] or something to format code on stackoverflow...all those indents are terrible.
Change load type to No wrap in - <body>
Here is updated fiddle
Here is Docs
If you open the browser console in JS fiddle it lists the error. The HTML can't find the JS.
This question already has answers here:
getAttribute() versus Element object properties?
(7 answers)
Closed 5 years ago.
I have a simple web-application with an input text field in it looking like this:
<input id="txtip" type="text" value="10.1.1.50" />
The address 10.1.1.50 is a default value for an ip address. And from javascript I would read it like this:
txtip.getAttribute("value")
Now let's suppose to change it to 10.1.1.49. In google chrome the above javascript code will still return 10.1.1.50, while the expression
txtip.value
returns 10.1.1.49.
What is the difference? What is the "right way"?
var el = document.getElementById('testBox');
$(document).focusout(function () {
alert('el.value = ' + el.value);
alert('el.getAttribute("value") = ' + el.getAttribute('value'));
e.preventDefault();
});
<h2>Change value in the text box</h2>
<input id="testBox" type="text" value="original value" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Found this on web might help you try following code type something and focusout
The difference is that element.value is real time and if a user changes let's say, a textbox input, it will reflect that, and show you the new value.
While getAttribute('value') will still show the original value="whateverWasHere" value.
I'm currently working my way through a beginner's JavaScript course on Treehouse and keep getting stuck on functions. In effort to understand better, I tried creating a calculator which converts human years to dog years. Here is my code so far:
HTML:
<div id="calculator">
<form>
<label>What is your current age in human years? <br>
<input type="text" id="humanYears"></label> <br>
<button type="text" id="calculate">Calculate</button>
</form>
</div>
JS:
function calculate() {
var humanYears = document.getElementById("humanYears").value;
var dogYears = (humanYears * 7);
document.write(dogYears);
}
document.getElementById("calculate").onclick = function(){calculate(); };
The page flickers and I keep seeing the form, no result.
I know this code is incorrect but I don't understand why. I also know I can just copy other people's code from Github and have a functioning calculator but that kind of defeats the purpose of learning. I would rather know why my code doesn't work and what I can do to fix it. (I double, triple checked that the HTML and JS files were properly linked, which they are.)
Any JS wizards out there care to chime in?
Edit: When I enter an age into the form, it merely reloads, rather than displaying the age in dog years (which is the desired outcome).
Your code works, although as you've indicated it's not great.
function calculate() {
var humanYears = document.getElementById("humanYears").value;
var dogYears = (humanYears * 7);
document.write(dogYears);
}
document.getElementById("calculate").onclick = function(){calculate(); };
<div id="calculator">
<form>
<label>What is your current age in human years? <br>
<input type="text" id="humanYears"></label> <br>
<button type="text" id="calculate">Calculate</button>
</form>
</div>
Some notes for improvement:
Avoid document.write
Forms should have submit buttons (either <input type="submit" value="Calculate"> or <button type="submit">Calculate</button>
The parentheses around your arithmetic are superfluous: var dogYear = humanYears * 7; is sufficient
Not everything needs an id attribute, although that makes DOM queries easy and quick
You should handle the form's submit event as opposed to the button's click event as you'll want to handle if, say, I submit the form by pressing Enter on my keyboard
You don't need the extra function around calculate, document.getElementById('calculate').onclick = calculate; would suffice
With those notes in mind, here's how I'd improve your calculator:
var form = document.getElementById('calculator');
function calculate() {
var years = form['humanYears'].value,
dogYears = years * 7;
document.getElementById('answer').innerText = dogYears;
}
form.addEventListener('submit', calculate, false);
<form id="calculator">
<p>
<label>
What is your current age in human years?<br>
<input type="text" name="humanYears">
</label>
</p>
<p>
<button type="submit">Calculate</button>
</p>
<p>
Answer: <span id="answer"></span>
</p>
</form>
Things I've changed:
I'm using <p> tags to control whitespace instead of <br> which will further let me customize presentation with CSS if I choose to. You cannot style <br> elements.
I'm modifying a portion of the DOM, not the entire DOM
I've bound my event handler with addEventListener which is way less obtrusive
I'm accessing form elements through the natural structure the DOM provides instead of running a full DOM query for each element
I've reduced some code
Here your working code with as little changes as possible:
<div id="calculator">
<form>
<label>What is your current age in human years? <br>
<input type="text" id="humanYears"></label> <br>
<button type="text" id="calculate">Calculate</button>
</form>
</div>
<script>
function calculate() {
var humanYears = document.getElementById("humanYears").value;
var dogYears = (humanYears * 7);
document.write(dogYears);
}
document.getElementById("calculate").onclick = function(){calculate(); return false; };
</script>
Assuming you put everything in one file the script tags are missing. If not then you still need a script tag to load the JS file.
Your function needed a "return false;". If you omit that, the page will reload after writing your output and won't see the output. That happens because the default behaviour of a button in a form is to reload the page. By returning "false" you suppress that.
The main problem is that document.write doesn't do what you imagine it does:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
See the documentation for document.write: https://developer.mozilla.org/en-US/docs/Web/API/Document/write
A better way to this is to have an empty element on the page, which you then change the contents of:
function calculate() {
var humanYears = document.getElementById("humanYears").value;
var dogYears = humanYears * 7;
document.getElementById('output').innerText = dogYears;
}
document.getElementById("calculate").onclick = calculate;
<div id="calculator">
<form>
<label>What is your current age in human years? <br>
<input type="text" id="humanYears">
</label>
<br>
<button type="button" id="calculate">Calculate</button>
<div id="output"></div>
</form>
</div>
I've also made some small improvements to your script:
Changed the indentation of your HTML to be more readable
Changed your button to have type="button" - otherwise your form will submit and the page will reload when you click the button. In this case, you actually don't even need a form element, but it's not hurting anything. Alternatively, you could add return false to your calculate function - this would tell the browser not to submit the form and thus not reload the page
Changed how you're adding the onclick handler - there's no need to wrap the calculate function in another function. In javascript, functions can actually be passed around like a variable. This is why I set the value of onclick to just be calculate - notice however that I left out the (). You want the onclick to be a reference to the function, otherwise the calculate function would be executed immediately, and the onclick would be set to the return value of the function - in this case, that would be undefined.