简体   繁体   中英

how to take user input in html and set it as a variable in js?

How would I take user input from html and set it to a variable in javascript?

This is what i'm trying to implement:

<p>
    <label>how old are you?</label>
     <form id="form" onsubmit="return false;">
      <input   style=position:absolute;top:80%;left:5%;width:40%; type="number" id="userInput">
      <input    style=position:absolute;top:50%;left:5%;width:40%; type="submit"    onclick="age()">
     </form>
    <script type="text/javascript">
      function age()
      {
        var input = document.getElementById("userInput");
        alert(input);
      }
      if(age<20)
      {
      alert(YOU ARE UNDER 20)
      }
    </script>
    </p>

With pure JavaScript:

var input = document.getElementById('userInput');
alert(input.value);

With jQuery:

var input = $('#userInput');
alert(input.val());

To achieve what you want:

function age() {
  var input = document.getElementById('userInput');
  var age = parseInt(input.value);

  if(age < 20) {
    alert('YOU ARE UNDER 20');
  }
}

There are some problems in your code. I will explain them. 1. You are creating a var input = document.getElementById("userInput"); But after that in your alert(input) it returns the entire object instead of the input value. 2. After that you are comparing Age wich is undefined because you didnt created var age = input; . If you compare input<20 it will work. In your alert you didnt use double quotes("") to create a string and alert that string. I hope its more clear now.

  function age() { var age = document.getElementById("userInput").value; alert(age); if(age<20) { alert("YOU ARE UNDER 20"); } } 
 <p> <label>how old are you?</label> <form id="form" onsubmit="return false;"> <input style=position:absolute;top:80%;left:5%;width:40%; type="number" id="userInput"> <input style=position:absolute;top:50%;left:5%;width:40%; type="submit" onclick="age()"> </form> </p> 

use document.getelementbyId

or

document.getelementbyclassname

alert(document.getElementById("userinput"));

or

alert( document.getElementsByClassName("classname"));

what are you trying to achieve? if you want to check age then move if inside function

  function age()
  {
    var age = document.getElementById("userInput").value;
    if(age<20)
    {
      alert("YOU ARE UNDER 20")
    }
  }

Try below

 function age() { var input = document.getElementById("userInput").value; if(input<20) { alert("YOU ARE UNDER 20"); } } 
 <p> <label>how old are you?</label> <form id="form" onsubmit="return false;"> <input type="number" id="userInput"> <input style=position:absolute;top:50%;left:5%;width:40%; type="submit" onclick="age()"> </form> </p> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM