How would I store the number in an html form input

2019-05-26 08:46发布

Basically what I want to do is when the user types a number in to an HTML form input field then presses the submit button, the number is stored in a javascript variable.

<input type="number" min="1" name="number">

var number = ?

How would I do this with javascript or with jquery?

Thank you.

3条回答
你好瞎i
2楼-- · 2019-05-26 09:12

Here is a javascript solution, only use this until jQuery comes built into your browser ( it might aswell be, seeing as it's the savior )

<form id="form">
  <input id="number" type="number" min="1" name="number">
  <button>Submit</button>
</form>

var form = document.getElementById('form');
    number = document.getElementById('number');
form.onsubmit = function() {
   var variable = number.value;
   alert( variable );
};

Just assign a submit handler, and get the value of the input.

My advice is to you though, please do not download jQuery just so you can store a variable.

查看更多
贪生不怕死
3楼-- · 2019-05-26 09:13

Here's your html,

<form id="form">
    <input type="number" min="1" name="number" />
    <input type="submit" value="submit">
</form>

With jQuery you can do this,

var number = 0;
var $form = $("#form");
var $input = $form.find("input[name=number]");

With some events you can add the value of the input to the number variable,

$form.submit(function(e){

    e.preventDefault();
    number = +($input.val()); 

    /* 
        takes value from input when the form is submitted. 
        This will work even when you hit "enter" on your keyboard.
    */

});

In summary,

<form id="form">
    <input type="number" min="1" name="number" />
    <input type="submit" value="submit">
</form>

<script>

    var number = 0;
    var $form = $("#form");
    var $input = $form.find("input[name=number]");

    $form.submit(function(e){

        e.preventDefault();

        number = +($input.val()); 

        /* 
            takes value from input when the form is submitted. 
            This will work even when you hit "enter" on your keyboard.
        */

        alert(number);

    });

</script>

Hope that helps!

查看更多
做自己的国王
4楼-- · 2019-05-26 09:16

A simple javascript solution is to do this.

var number = document.getElementById("number").value;

This saves the value of the text box under the name 'number'. If you know javascript you can then use it to do pretty much anything. Hope this helps.

Please note that to do this, you need to use id="number" , instead of name="number".

Complete code could be something like

<input type="number" id="number" onchange="save()">

this means that as soon as the user inputs a number, the save() function will be called in the javascript file.

javascript

function save() {
      var number;
      number = document.getElementById("number").value;
      // Do whatever you want with the value here.
}
查看更多
登录 后发表回答