Moving a focus when the input text field reaches a max length

微笑、不失礼 提交于 2019-11-27 07:07:07
Tauren

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>

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.

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.

I highly recommend using the Masked Input jQuery plugin. http://digitalbush.com/projects/masked-input-plugin/

Your usage will look like this:

$('#creditCardNumber').mask("9999-9999-9999-9999");

This way you'll have copy-paste support.

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)"/>

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>

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();
    }
}

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!