首页 > 解决方案 > 基于 Javascript 中的用户输入获取输入表单的值和 id 的函数

问题描述

我有几个输入。当用户在输入中输入内容时,我想使用函数获取其值和 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>

标签: javascripthtmlformsfunctioninput

解决方案


使用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


推荐阅读