【问题标题】:Getting data from input using JavaScript使用 JavaScript 从输入中获取数据
【发布时间】:2015-08-28 11:58:19
【问题描述】:

我正在尝试使用 JavaScript 从<input type='num'> 中获取值我正在使用以下代码:

Choose a number between 1 and 5 <input type='num' name="input">

<button id="btn">Click me!</button>

<script>
    var input;

    document.getElementById('btn').onclick = function(){
    input = document.getElementById('num');
        alert(input); //To check what value input has
</script>

这应该得到一个值,但我只是得到一个 null 我做错了什么?

【问题讨论】:

  • getElementById('num') 具有该 ID 的元素在哪里?
  • document.getElementById() 应该返回 null 如果没有找到具有指定 id 的元素 。但无论如何,显示的代码是不完整的,不会运行。
  • 这和数据库有什么关系?
  • 使用这个小提琴jsfiddle.net/nvtc7k68
  • 对不起,我正在使用这个来获取 id 的数据库忘记编辑名称,谢谢大家的帮助

标签: javascript html


【解决方案1】:

您尚未定义您的id。另外我猜你的输入类型应该是number

<input type='number' name="input" id="num">
       ^^^^^^^^^^^^               ^^^^^^^^

alert它的值你需要使用

alert(input.value) //.value is used to get value of input

【讨论】:

    【解决方案2】:

    你的代码有不止一个问题

    1) 你必须关闭你的函数的括号 应该是

     document.getElementById('btn').onclick = function(){
        input = document.getElementById('num');
            alert(input); //To check what value is outputted
    }  
    

    2)

    input = document.getElementById('num');
    

    getElementById() 方法返回具有 ID 的元素 具有指定值的属性。

    所以 ID 属性在这里是必不可少的,在你的代码中没有定义 ID 属性,所以你必须先定义它

    喜欢

    <input type='number' id="num" name="input">
    

    3) document.getElementById('num'); 不返回输入字段的值 它返回对象 因此,如果您想要价值,请使用以下代码

    document.getElementById('num').value;
    

    4) 你的input type="number"

    对于所需的输出,您可以使用以下代码

    Choose a number between 1 and 5 <input type='number' name="input" id="myid">
    
    <button id="btn">Click me!</button>
    

    JS

        var myButton = document.getElementById("btn");
    myButton.onclick = function()
    {
             alert(document.getElementById("myid").value); //where does id come from?
    }
    

    上面的方法是纯JS,如果需要jquery方法可以参考下面

    $( "#btn" ).click(function() {
      var input=$("#myid").val();
        alert(input)
    });
    

    【讨论】:

      【解决方案3】:

      getElementById() 作用于具有id 属性的元素。因此,由于您没有在 input 类型中添加 id 属性,因此无法找到带有 id=num 的元素。
      只需在 input 元素中添加 id="num" 即可。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-09
        • 2016-09-30
        • 1970-01-01
        • 1970-01-01
        • 2021-06-14
        • 1970-01-01
        相关资源
        最近更新 更多