我有这个代码,它可以从数据库中通过ajax检索数据,并且可以添加无限的文本字段:
<div class="input" id="itemRows">
<div class="clone">
<style>
.txtHint {
width:95%;
padding:10px 6px;
border-bottom:solid 3px #06C;
background-color:#f1f1f1;
margin-right:5px;
}
</style>
<input onchange="showUser(this.value)" type="text" class="clientphone" placeholder="رقم العميل" name="clientmergedid[]" />
<input type="text" class="clientdes" placeholder="صفة العميل" name="clientmergeddes[]" />
<div class="clearfloat"></div>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "searchuser/getuser.php?clientmergedid=" + str, true);
xmlhttp.send();
}
</script>
<div id="txtHint" class="txtHint">بيانات العميل</div>
<div class="clearfloat"></div>
</div> <a href="#" class="add" rel=".clone">إضافة المزيد</a>
<script type="text/javascript">
$(function() {
var removeLink = ' <a class="remove" href="#" onclick="$(this).parent().slideUp(function(){ $(this).remove() }); return false">إزالة</a>';
$('a.add').relCopy({
append: removeLink
});
});
</script>
<div class="clearfloat"></div>
<input onClick="addRow(this.form);" class="clientadd" type="button" value="جديد" />
<div class="clearfloat"></div>
</div>
问题是它只能检索第一个txtHint
div的数据。如何为其他输入做同样的事情?
答案 0 :(得分:1)
对于您的初始问题,为每个输入提供一个类,然后将change
hander绑定到该类的元素。这样你可以有任意数量的输入具有这种行为:
<input class="my_class" type="text">
<input class="my_class" type="text">
jQuery(function () {
jQuery('.my_class').on('change', function () {
var the_input = jQuery(this);
console.log("My new value is " + the_input.val());
/// your ajax code goes here, and has access to the_input
});
});
此处为例:http://jsfiddle.net/3k3TL/
此外,由于您似乎已经在使用jQuery,我建议您使用它的.get()方法进行ajax调用而不是现有代码。