Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

html - Limit the number of characters in a separate input field for each character

I have an input field and would want to give it a look and feel of a character-by-character box field (image below).

enter image description here

My HTML and CSS are written below. They work fine except the max length I want the user to enter is 6. When the user enters the 6th character, the boxes move out of place, even though the 7th character is NOT added to the field. How can I avoid this?

First 5 characters added:

enter image description here

6th character added, the alignment is out:

enter image description here

HTML:

<input type="text" maxlength="6" id="text"/>

CSS:

#text{
    background-image:
    url("http://3.bp.blogspot.com/-4oAWWCcNNz4/Tjr3nKNyVUI/AAAAAAAAPLU/Pouua-pNsEY/s1600/sq.gif");    
    width: 114px;
    height: 18px;
    background-size: 20px;
    border: none;
    font-family: monospace;
    font-size: 13px;
    padding-left: 5px;
    letter-spacing: 12px;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using some JS you can blur the input.

Obs.: I did some adjusts in css..

$(document).ready(function(){
$("#text").on('keypress', function(e){
  if($(this).val().length > 4) {
    var value = $(this).val() + String.fromCharCode(e.keyCode);
      $(this).val(value);
    $(this).blur();
    }
  });
});
#text{
    background-image:
    url("http://3.bp.blogspot.com/-4oAWWCcNNz4/Tjr3nKNyVUI/AAAAAAAAPLU/Pouua-pNsEY/s1600/sq.gif");    
    width: 114px;
    height: 18px;
    background-size: 20px;
    border: none;
    font-family: monospace;
    font-size: 13px;
    padding-left: 6.5px;
    letter-spacing: 13px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" maxlength="6" id="text"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...