+ 7
how to take input in java script by input tag of HTML? Please explain.
5 Respostas
+ 3
your issue is that you are trying to reference an object before it has been loaded, and also it is .value not .Value, try this instead
https://code.sololearn.com/WhbYXnwJOuRq/?ref=app
+ 3
Tom has a great answer, but let me explain how it works:
first, learn how browsers load a web page:
1. load head
2.load body
Sololearn puts the script in the head meaning it gets loaded before the body loads. to fix this, make a function (i recommend you to call it "init") then give the body the "onload" attribute the body should look like this:
<body onload="init()">
and the script should look like this:
function init()
{
//insert your code here
}
*Tip:*
if you add the "defer" attribute the script will load only when the body has loaded.
+ 2
Hey, Tom what i use when I want to take multiple inputs
+ 1
both of the answers are correct, but lemme explain this further:
you're simply assigning your id to a variable before it is even loaded, so it gives you a null value. so you have to load everything, then start your script:
window.onload = function() {
// your code here
}
After you load your page first then your script, your output won't appear unless you add an event listener and handle that event when it happens:
eg:
document.getElementById('element-id').onchange = function () {
console.log('output');
}
here is the same code, just added what I mentioned above: https://code.sololearn.com/W6018ZSz6Pm0/#html
0
You just add another input element (with a different id) to the body, and in the function you add
var a = document.getElementById(id).value;
(changing id to the id you assigned to the new input