简体   繁体   English

根据用户在Javascript中的输入获取输入表单的值和id的函数

[英]a function to get value and id of an input form based on user input in Javascript

I have several inputs.我有几个输入。 When a user enters something in an input I want to get its value and id using a function.当用户在输入中输入内容时,我想使用函数获取其值和 id。 What's the best way to do it?最好的方法是什么?

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

Using change/keyup/keydown event (which can be replaced to another event if needed) you can do something like this:使用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">

And for your JS而对于你的 JS

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

Here's a JSFiddle .这是一个JSFiddle

try this.尝试这个。 whenever you type something(include backspace), the key event onkeyup is fired and getIdVal function will be called.每当您键入内容(包括退格键)时,都会触发键事件 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>

<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);

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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