将Jquery函数与具有相同ID的多个文本字段一起使用 [英] Using Jquery functions with Multiple Text Fields With Same ID
问题描述
我正在寻求有关如何使用javascript生成的jquery引用特定文本字段的帮助.
I looking for help on how to reference specific text fields with jquery that are generated with javascript.
我得到的仅适用于字段引用的第一个实例.
What I get works only on the first instance of the field reference.
HTML代码:
Record ID<input type="text" name="ri[]" id="ri1" size="7" style="font-size:0.9em;">
Qty Per Box<input type="text" name="qpb[]" id="qpb1" size="7" style="font-size:0.9em;">
用于生成更多行的Javascript
Javascript Used To Generate More Rows Like Above
<!--Dynamically Create New Rows For Data Entry-->
<script language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true === chkbox.checked) {
if(rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</script>
所以我最终得到的是具有相同ID/名称的多行.我只想做的是验证keyup上的输入,因此我决定使用(this).val方法,但它仅适用于第一行.
So what I end up getting is multiple rows with the same id / name. What I simply want to do is validate input on keyup so I decided to use the (this).val method but it only works on the first row.
<script>
$(document).ready(function() {
$("#ri1").keyup(function() {
$(this).val($(this).val().replace(/[^\d]/g, ""));
});
});
</script>
有人以这种方式生成多行输入字段时,知道一种更好的验证输入的解决方案吗?
Anybody know a better solution to validating input on when generating multiple rows of input fields this way?
Js小提琴 http://jsfiddle.net/nS2LM/22/
推荐答案
不建议多次使用ID,但是如果您使用的是最新的jQuery,则事件委派是您的答案:
Using an ID more than once is not recommended but if you are using the latest jQuery then event delegation is your answer:
<input type="text" name="ri[1]" id="ri1" size="7" style="font-size:0.9em;" class="do_stuff">
<input type="text" name="ri[2]" id="ri2" size="7" style="font-size:0.9em;" class="do_stuff">
<script>
$(document).ready(function() {
$('body').on('keyup', '.do_stuff', function() {
$(this).val($(this).val().replace(/[^\d]/g, ""));
});
});
</script>
上面的代码将keyup绑定到主体的子.do_stuff元素,因此,任何具有.do_stuff类的动态创建的元素都将被keyup事件捕获.
The code above binds keyup to the body's child .do_stuff elements so any dynamically created elements with a class of .do_stuff will be caught by the keyup event.
这篇关于将Jquery函数与具有相同ID的多个文本字段一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!