【问题标题】:a function to get value and id of an input form based on user input in Javascript基于 Javascript 中的用户输入获取输入表单的值和 id 的函数
【发布时间】:2019-02-15 15:54:33
【问题描述】:

我有几个输入。当用户在输入中输入内容时,我想使用函数获取其值和 id。最好的方法是什么?

<input type="number" class="form-control" id="id1">
<input type="number" class="form-control" id="id2">
.
.
<input type="number" class="form-control" id="id9">
<input type="number" class="form-control" id="id10">



<script>
function getIdVal(){
// how to get those values and ids from this function?
}
</script>

【问题讨论】:

  • “当用户输入内容时......”你能澄清一下吗?你的意思是每次击键,还是什么?
  • 所以添加一个事件监听器并读取值。基本的 JavaScript 概念。

标签: javascript html forms function input


【解决方案1】:

使用change/keyup/keydown 事件(如果需要,可以替换为另一个事件),您可以执行以下操作:

<input type="number" class="form-control" onchange="run(this)" id="id1">
<input type="number" class="form-control" onchange="run(this)" id="id2">

<input type="number" class="form-control" onchange="run(this)" id="id9">
<input type="number" class="form-control" onchange="run(this)" id="id10">

对于你的 JS

function run(ele){
  var id = ele.id;
  var value = ele.value;
  console.log(id, value);
}

这是JSFiddle

【讨论】:

    【解决方案2】:

    试试这个。每当您键入内容(包括退格)时,都会触发键事件 onkeyup 并调用 getIdVal 函数。

    <input type="number" class="form-control" onkeyup="getIdVal(this)" id="id1">
    <input type="number" class="form-control" onkeyup="getIdVal(this)" id="id2">
    .
    .
    <input type="number" class="form-control" onkeyup="getIdVal(this)" id="id9">
    <input type="number" class="form-control" onkeyup="getIdVal(this)" id="id10">
    
    
    
    <script>
    function getIdVal(obj) {
        // how to get those values and ids from this function?
        console.log(obj.id)
        console.log(obj.value)
    }
    </script>

    【讨论】:

      【解决方案3】:
      <input type="text" id="fname1" onkeyup="myFunction('fname1');">
      <input type="text" id="fname2" onkeyup="myFunction('fname2');">
      
       function myFunction(ids) {
          var x = document.getElementById(ids);
         alert("Value: "+x.value  + "  ID: "+x.id);
      

      }

      【讨论】:

      • 欢迎来到 Stack Overflow!感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation would greatly improve its long-term value 通过展示为什么这是解决问题的好方法,并使其对有其他类似问题的未来读者更有用。请编辑您的答案以添加一些解释,包括您所做的假设。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多