当输入文本字段达到最大长度时移动焦点

发布于 2024-08-15 22:29:48 字数 1121 浏览 2 评论 0原文

我有一张信用卡号码表。该号码分为四个部分,就像真正的信用卡一样。

我想向表单添加 JavaScript 风格,当用户在字段中键入四个字母时,焦点会自动转到下一个标签。但不在最后一个标签中。通过这样做,用户不必键入“tab”键来移动焦点。

可以在标签中添加一些额外的类、id 或名称。

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>MoveFocus</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript" charset="utf-8">
     $(function() {
     // some code goes here.
    });
    </script>
</head>


<body>
  <form action="post.php" method="post" accept-charset="utf-8">
    <input type="text" value="" id="first" size="4" maxlength="4"/> -
    <input type="text" value="" id="second" size="4" maxlength="4"/> -
    <input type="text" value="" id="third" size="4" maxlength="4"/> -
    <input type="text" value="" id="fourth" size="4" maxlength="4"/>
    <p><input type="submit" value="Send Credit Card"></p>
  </form>
</body>
</html>

I do have a credit card number form. The number is divided into four parts just as on a real credit card.

I want to add a JavaScript taste to the form where when a user types four letters in a field, the focus automatically goes to the next tag. But not in the last tag. By doing this, a user doesn't have to type "tab" key to move a focus.

It is okay to add some extra class, id or name in the tags.

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>MoveFocus</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript" charset="utf-8">
     $(function() {
     // some code goes here.
    });
    </script>
</head>


<body>
  <form action="post.php" method="post" accept-charset="utf-8">
    <input type="text" value="" id="first" size="4" maxlength="4"/> -
    <input type="text" value="" id="second" size="4" maxlength="4"/> -
    <input type="text" value="" id="third" size="4" maxlength="4"/> -
    <input type="text" value="" id="fourth" size="4" maxlength="4"/>
    <p><input type="submit" value="Send Credit Card"></p>
  </form>
</body>
</html>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

抹茶夏天i‖ 2024-08-22 22:29:48

我以前没有使用过这个工具,但它可以满足您的要求。您可以查看它的源代码以获得一些想法:

GitHub 上的此插件

对于您的情况,您将添加此代码:

<script type="text/javascript" src="jquery.autotab.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('#first').autotab({ target: '#second', format: 'numeric' });
    $('#second').autotab({ target: '#third', format: 'numeric', previous: '#first' });
    $('#third').autotab({ previous: '#second', format: 'numeric' });
});
</script>

I haven't used this tool before, but it does what you want. You could just look at it's source to get some ideas:

This Plugin on GitHub

For your situation, you would add this code:

<script type="text/javascript" src="jquery.autotab.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('#first').autotab({ target: '#second', format: 'numeric' });
    $('#second').autotab({ target: '#third', format: 'numeric', previous: '#first' });
    $('#third').autotab({ previous: '#second', format: 'numeric' });
});
</script>
独行侠 2024-08-22 22:29:48

正如其他人所敦促的,不要这样做。用户将无法预料到您会自动标记他们,这会让他们发疯。您是否考虑过复制并粘贴信用卡的用户?无论如何,使用四个字段有什么好处?

此外,并非所有信用卡都将其号码分为四组,每组四个。例如,美国运通将它们分为三组数字。在这种情况下,动态添加和删除文本字段会带来麻烦。

相反,使用 Javascript 自动在它们所属的位置插入空格,前进光标,而不是焦点。数字中的第一位数字表示信用卡的类型(5 是 Mastercard、4 是 Visa、3 是 American Express...),因此您可以阅读此信息来决定在哪里添加空格。发布字符串时,请擦掉字符串中的空格。这种方法将为您和您的用户减轻很多痛苦。

As others have urged, don’t do this. Users are not going to be able to anticipate that you’ll auto-tab them, and this will drive them nuts. Have you thought about users who copy and paste their credit card? What is the benefit of using four fields anyway?

Also, not all credit cards divide their numbers into four sets of four. American Express divides them into three groups of numbers, for example. Dynamically adding and removing text fields is asking for trouble in this case.

Instead, use your Javascript to automatically insert the spaces where they belong, advancing the cursor, not the focus. The first digit in the number indicates the type of credit card (5 is Mastercard, 4 is Visa, 3 is American Express…), so you can read this to decide where to add the spaces. Scrub the spaces out of the string when you post it. This approach will save you and your users a lot of pain.

智商已欠费 2024-08-22 22:29:48

正如 @Sander 所建议的,执行自动选项卡的简单方法是:

jQuery("form input[type=text]").on('input',function () {
    if(jQuery(this).val().length == jQuery(this).attr('maxlength')) {
        jQuery(this).next("input").focus();
    }
});

Update by @morespace54

oninputhtml5 事件,支持 < strong>IE9+,因此您可以使用keyup代替。

As @Sander suggested, the easy way to do an auto-tab is:

jQuery("form input[type=text]").on('input',function () {
    if(jQuery(this).val().length == jQuery(this).attr('maxlength')) {
        jQuery(this).next("input").focus();
    }
});

Update by @morespace54

oninput is an html5 event is supported on IE9+, so you can use keyup instead.

望笑 2024-08-22 22:29:48

如果您的表单字段像示例中那样一个挨着一个,您可以简单地利用 nextElementSibling ,瞧!

function skipIfMax(element) {
  max = parseInt(element.dataset.max)
  
  
  if (element.value.length >= max && element.nextElementSibling) {
    element.nextElementSibling.focus();  
  }
}
<input type="text" data-max=2 oninput="skipIfMax(this)"/>
<input type="text" data-max=3 oninput="skipIfMax(this)"/>
<input type="text" data-max=4 oninput="skipIfMax(this)"/>
<input type="text" data-max=5 oninput="skipIfMax(this)"/>

If your form fields are one beside the other like in your example, you could simply take advantage of nextElementSibling and voilà!

function skipIfMax(element) {
  max = parseInt(element.dataset.max)
  
  
  if (element.value.length >= max && element.nextElementSibling) {
    element.nextElementSibling.focus();  
  }
}
<input type="text" data-max=2 oninput="skipIfMax(this)"/>
<input type="text" data-max=3 oninput="skipIfMax(this)"/>
<input type="text" data-max=4 oninput="skipIfMax(this)"/>
<input type="text" data-max=5 oninput="skipIfMax(this)"/>

遗失的美好 2024-08-22 22:29:48

我强烈建议使用 屏蔽输入jQuery 插件

您的用法将如下所示:

$("#CreditCardNumber").mask("9999-9999-9999-9999");

这样您将获得复制粘贴和占位符支持。

I highly recommend using the Masked Input jQuery Plugin.

Your usage will look like this:

$("#CreditCardNumber").mask("9999-9999-9999-9999");

This way you'll have copy-paste and placeholder support.

情丝乱 2024-08-22 22:29:48

一个非常简单的解决方案可以是这样的:

<script type="text/javascript">
    function input_onchange(me){ 
        if (me.value.length != me.maxlength){
            return;
        }
        var i;
        var elements = me.form.elements;
        for (i=0, numElements=elements.length; i<numElements; i++) {
            if (elements[i]==me){
                break;
            }
        }
        elements[i+1].focus();
    }
</script>
<form action="post.php" method="post" accept-charset="utf-8">
    <input type="text" value="" id="first" size="4" maxlength="4"
        onchange="input_onchange(this)"
    /> -
    <input type="text" value="" id="second" size="4" maxlength="4"
        onchange="input_onchange(this)"
    /> -
    <input type="text" value="" id="third" size="4" maxlength="4"
        onchange="input_onchange(this)"
    /> -
    <input type="text" value="" id="fourth" size="4" maxlength="4"
        onchange="input_onchange(this)"
    /> -
    <p><input type="submit" value="Send Credit Card"></p>
</form>

A very simple solution could go like this:

<script type="text/javascript">
    function input_onchange(me){ 
        if (me.value.length != me.maxlength){
            return;
        }
        var i;
        var elements = me.form.elements;
        for (i=0, numElements=elements.length; i<numElements; i++) {
            if (elements[i]==me){
                break;
            }
        }
        elements[i+1].focus();
    }
</script>
<form action="post.php" method="post" accept-charset="utf-8">
    <input type="text" value="" id="first" size="4" maxlength="4"
        onchange="input_onchange(this)"
    /> -
    <input type="text" value="" id="second" size="4" maxlength="4"
        onchange="input_onchange(this)"
    /> -
    <input type="text" value="" id="third" size="4" maxlength="4"
        onchange="input_onchange(this)"
    /> -
    <input type="text" value="" id="fourth" size="4" maxlength="4"
        onchange="input_onchange(this)"
    /> -
    <p><input type="submit" value="Send Credit Card"></p>
</form>
枫以 2024-08-22 22:29:48

我还没有测试过,但我认为这会起作用。当第四个字段完成时,它也可能会将焦点移动到按钮。

$("form input").change(function () {
    var maxLength = $(this).attr('maxlength');

    if($(this).val().length == maxLength) {
        $(this).next().focus();
    }
}

I haven't tested it, but I think this will work. It will probably also move the focus to the button when the 4th field is completed.

$("form input").change(function () {
    var maxLength = $(this).attr('maxlength');

    if($(this).val().length == maxLength) {
        $(this).next().focus();
    }
}
尐籹人 2024-08-22 22:29:48

它没有四个字段,但它确实验证信用卡(完整性检查,而不是 Luhn 算法!)。我必须告诉您为用户和自动标签使用多个字段是多么烦人。我建议您只使用一个字段。

来自 jquery 网站:

$("#myform").validate({
  rules: {
    field: {
      required: true,
      creditcard: true
    }
  }
});

/

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/lib/jquery.delegate.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script type="text/javascript">
jQuery.validator.setDefaults({
    debug: true,
    success: "valid"
});;
</script>

  <script>
  $(document).ready(function(){
    $("#myform").validate({
  rules: {
    field: {
      required: true,
      creditcard: true
    }
  }
});
  });
  </script>
  <style>#field { margin-left: .5em; float: left; }
    #field, label { float: left; font-family: Arial, Helvetica, sans-serif; font-size: small; }
    br { clear: both; }
    input { border: 1px solid black; margin-bottom: .5em;  }
    input.error { border: 1px solid red; }
    label.error {
        background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/unchecked.gif') no-repeat;
        padding-left: 16px;
        margin-left: .3em;
    }
    label.valid {
        background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif') no-repeat;
        display: block;
        width: 16px;
        height: 16px;
    }
</style>
</head>
<body>

<form id="myform">
  <label for="field">Required, creditcard (try 446-667-651): </label>
  <input class="left" id="field" name="field" />
  <br/>
  <input type="submit" value="Validate!" />
</form>

</body>
</html>

This does not have four fields, but it does validate credit cards (integrity check, not Luhn's Algorithm!). I have to tell you how annoying it is to use multiple fields for a user and auto-tabbing. I recommend you only use one field.

From jquery website:

$("#myform").validate({
  rules: {
    field: {
      required: true,
      creditcard: true
    }
  }
});

/

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/lib/jquery.delegate.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script type="text/javascript">
jQuery.validator.setDefaults({
    debug: true,
    success: "valid"
});;
</script>

  <script>
  $(document).ready(function(){
    $("#myform").validate({
  rules: {
    field: {
      required: true,
      creditcard: true
    }
  }
});
  });
  </script>
  <style>#field { margin-left: .5em; float: left; }
    #field, label { float: left; font-family: Arial, Helvetica, sans-serif; font-size: small; }
    br { clear: both; }
    input { border: 1px solid black; margin-bottom: .5em;  }
    input.error { border: 1px solid red; }
    label.error {
        background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/unchecked.gif') no-repeat;
        padding-left: 16px;
        margin-left: .3em;
    }
    label.valid {
        background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif') no-repeat;
        display: block;
        width: 16px;
        height: 16px;
    }
</style>
</head>
<body>

<form id="myform">
  <label for="field">Required, creditcard (try 446-667-651): </label>
  <input class="left" id="field" name="field" />
  <br/>
  <input type="submit" value="Validate!" />
</form>

</body>
</html>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文