文本框输入完成自动跳入下一个代码实例

快乐打工仔 分类:实例代码

分享一段代码实例,它实现了当文本框内容输入完成自动跳入下一个的功能。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<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()一章节。

文本框输入完成自动跳入下一个代码实例,这样的场景在实际项目中还是用的比较多的,关于文本框输入完成自动跳入下一个代码实例就介绍到这了。

文本框输入完成自动跳入下一个代码实例属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容