文本框輸入事件:onchange 、onkeyup 、onblur
onchange在用於文本框輸入框時,有一個明顯的不足. 事件不會隨着文字的輸入而觸發,而是等到文本框失去焦點(onblur)時才會觸發. 也就是沒有即時性!
為了達到在文本框中輸入內容后,立即觸發事件,可以用onkeyup事件,
在IE下,可以用onpropertychange來代替onchange事件,當文本框有任何變化時,能立即觸發此事件.
兼容瀏覽器可以用oninput事件,谷歌瀏覽器、IE10測試沒問題 沒測試是否兼容其他瀏覽器
下面附上我自己做的一個例子
需求:輸入文本框后,檢索下拉框選項,匹配則設為選中項,不匹配則把選中項改成默認第一個
方法一:使用onkeyup
<script language="javascript">
//因為是嵌套在母板頁中,所以獲取下拉框這樣寫:$("#<%=ddlCountry.ClientID%>"),如果不嵌套在母板頁,可以這樣寫:$("#ddlCountry")
function Search() {
var countryCount = 0; //國家總個數
var notEqualCount = 0;//輸入內容與國家不匹配的個數
$("#<%=ddlCountry.ClientID%>").each(function () {
$(this).find("option").each(function () {
countryCount++;
if ($(this).val() == $("#txtTest").val() || $(this).text() == $("#txtTest").val()) {//文本框的值與下拉框的value、text對比
$(this).attr("selected", "selected"); //選中
} else {
notEqualCount++;
}
});
});
if (countryCount != 0 && notEqualCount != 0 && countryCount == notEqualCount) {//輸入的值與下拉框的值不匹配
$("#<%=ddlCountry.ClientID%>").get(0).selectedIndex = 0;
}
}
</script>
國家:<asp:DropDownList ID="ddlCountry" runat="server"></asp:DropDownList>
<input type="text" id="txtTest" onkeyup="Search()" />
方法二:使用oninput事件
<script language="javascript">
$(document).ready(function () {
$('#txtTest').bind('input', function () {//給文本框綁定input事件
if ($('#txtTest').val().trim() != "") {
var countryCount = 0; //國家總個數
var notEqualCount = 0; //輸入內容與國家不匹配的個數
$("#<%=ddlCountry.ClientID%>").each(function() {
$(this).find("option").each(function() {
countryCount++;
if ($(this).val() == $("#txtTest").val() || $(this).text() == $("#txtTest").val()) {
$(this).attr("selected", "selected");
} else {
notEqualCount++;
}
});
});
if (countryCount != 0 && notEqualCount != 0 && countryCount == notEqualCount) {
$("#<%=ddlCountry.ClientID%>").get(0).selectedIndex = 0;
alert("沒有您輸入的國家");
}
}
});
});
國家:<asp:DropDownList ID="ddlCountry" runat="server"></asp:DropDownList>
<input type="text" id="txtTest" />
參考文章:http://koyoz.com/blog/?action=show&id=225
http://calefy.org/2012/11/12/javascript-key-events-and-input-control.html