how to take input in java script by input tag of HTML? Please explain. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

how to take input in java script by input tag of HTML? Please explain.

https://code.sololearn.com/WqzAp4d33OU5/?ref=app

24th Jan 2020, 5:26 AM
Avinash
Avinash - avatar
5 Answers
+ 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
24th Jan 2020, 11:08 AM
Tom
Tom - avatar
+ 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.
24th Jan 2020, 7:41 PM
doonv
doonv - avatar
+ 2
Hey, Tom what i use when I want to take multiple inputs
25th Jan 2020, 8:29 AM
Avinash
Avinash - avatar
+ 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
25th Jan 2020, 7:06 AM
Youssef Hammad
Youssef Hammad - avatar
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
25th Jan 2020, 10:14 AM
Tom
Tom - avatar