[英]a function to get value and id of an input form based on user input in Javascript
我有幾個輸入。 當用戶在輸入中輸入內容時,我想使用函數獲取其值和 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>
使用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 。
嘗試這個。 每當您鍵入內容(包括退格鍵)時,都會觸發鍵事件 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.