开发者

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

开发者 https://www.devze.com 2022-12-14 16:31 出处:网络
I do have a credit card number form. The number is divided into four parts just as on a real credit card.

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/javasc开发者_如何学Pythonript" 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 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.


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


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.


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消