文字框輸入完成自動跳入下一個程式碼例項

antzone發表於2017-04-18

分享一段程式碼例項,它實現了當文字框內容輸入完成自動跳入下一個的功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
.input input {
  display: inline-block;
}
.input {
  width: 580px;
  height: 41px;
  line-height: 41px;
  margin-right: 20px;
}
.input input {
  border: 1px solid #ccc;
  width: 100px;
  height: 40px;
  outline: none;
  font-size: 14px;
  font-weight: inherit;
  text-align: center;
  line-height: 40px;
  color: #000;
  background: #fff;
  margin-right: 10px;
  margin-left: 10px;
}
.input:first-child {
  margin-left: 0;
}
</style>
<script src="http://www.lanrenzhijia.com/ajaxjs/jquery.min.js"></script>
<script>
$(document).ready(function() {
  $("#sn1").focus();
  $("input[name^='sn']").each(function() {
    var that = $(this);
    that.keyup(function() {
      if(that.val().length === 3){
        if (that.val().trim().length < 3) {
          var TheVal = that.val().trim();
          that.val(TheVal)
        } else {
          that.next().focus();
        }
      }
    })
  });
});
</script>
</head>
<body>
  <div class="input" id="coupon">
    <input type="tel" placeholder="紅" name="sn1" maxlength="3" id="sn1"> - 
    <input type="tel" placeholder="包" name="sn2" maxlength="3" id="sn2"> -
    <input type="tel" placeholder="密" name="sn3" maxlength="3" id="sn3"> -
    <input type="tel" placeholder="鑰" name="sn4" maxlength="3" id="sn4">
  </div>
</body>
</html>

上面的程式碼實現了我們的要求,下面介紹一下它的實現過程。

一.程式碼註釋:

(1).$(document).ready(function() {}),當文件結構完全載入完畢再去執行函式中的程式碼。

(2).$("#sn1").focus(),預設第一個文字框獲取焦點。

(3).$("input[name^='sn']").each(function() {}),遍歷每一個name屬性值以sn開頭的input元素。

(4).var that = $(this),將當前input元素轉換為對應的jQuery物件,並賦值給變數that。

(5).that.keyup(function() {}),為當前input元素註冊keyup事件處理函式。

(6).if(that.val().length === 3)判斷當前文字框的值的長度是否等於3。

(7).if (that.val().trim().length < 3) {

  var TheVal = that.val().trim();

  that.val(TheVal)

} else {

  that.next().focus();

},如果刪除兩端空格之後,長度小於3,那麼就將文字框的值重置為去除空格後的值。

否則的話,當前文字框緊鄰的下一個同輩元素將獲取焦點。

二.相關閱讀:

(1).focus()可以參閱jQuery focus事件一章節。

(2).[name^='sn']可以參閱jQuery [attribute^=value]一章節。

(3).each()可以參閱jQuery each()一章節。

(4).keyup事件可以參閱jQuery keyup事件一章節。

(5).trim()可以參閱javascript trim()一章節。

(6).next()可以參閱jQuery next()一章節。

相關文章