HTML code of text box input 0000000-0000
Basically I have an HTML textbox and the user enters numbers. I want to automatically put a - after the 7th digit Basically, this pattern:
0000000-0000
<input type="text" class="form-control width-160" name="value" required maxlength="10"/>
I'm sure I need to use a regex for this, but can I use it directly in HTML or do I need jQuery?
source to share
You can use jquery.mask
for this
Read more here
Using:
<input type="text" class="phone" name="value"/>
$(document).ready(function(){
$('.phone').mask('0000000-0000');
});
See it live here https://jsfiddle.net/n0oeu3p2/
source to share
Try with slice()
and change input length
to11
$('input').on('input',function(){
var str = $(this).val().replace('-','');
if(str.length > 7)
$(this).val(str.slice(0,7)+'-'+str.slice(7,str.length))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control width-160" name="value" required maxlength="11" />
source to share
<form action="javascript:alert('Corect!');">
<input type="text" pattern="\d{7}-\d{4}" title="Should be of the format 0000000-0000"/>
</form>
Done! With html and regexp only
Without using any external library, you can use event onkeyup
and just check if we are going to put the 7th append character -
into the value.
Here you will need:
var changeIt = function changeIt(input) {
if (input.value.length === 7) {
input.value = input.value + "-";
}
}
Demo:
Here's a working snippet:
var changeIt = function changeIt(input) {
if (input.value.length === 7) {
input.value = input.value + "-";
}
}
<input type="text" class="form-control width-160" name="value" required maxlength="12" onkeyup="changeIt(this)" pattern="[0-9]{7}-[0-9]{4}" />
And use [0-9]{7}-[0-9]{4}
it as a regex in an pattern
HTML attribute to make sure your input matches the Regex 0000000-0000
.
source to share