I have this input
<input type="tel" class="form-control" id="inputTelephone" placeholder="123-456-7890 Format" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" maxlength="12">
And have this jQuery code
$(function () {
$('#inputTelephone').keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$text = $(this);
if (key !== 8 && key !== 9) {
if($text.val().indexOf('′') === 1){
$text.val($text.val().replace(/[($)s._-]+/g, ''));
}
if ($text.val().length === 3) {
$text.val($text.val() + '-');
}
if ($text.val().length === 7) {
$text.val($text.val() + '-');
}
}
return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
})
});
So far works flawless but when I type "′" or "`" it is shown
I saw on this link that here works properly (no accent characters shown)
https://webdesign.tutsplus.com/tutorials/auto-formatting-input-value--cms-26745
I'll better put the code that works on that link
(function($, undefined) {
"use strict";
// When ready.
$(function() {
var $form = $( "#form" );
var $input = $form.find( "input" );
$input.on( "keyup", function( event ) {
// When user select text in the document, also abort.
var selection = window.getSelection().toString();
if ( selection !== '' ) {
return;
}
// When the arrow keys are pressed, abort.
if ( $.inArray( event.keyCode, [38,40,37,39] ) !== -1 ) {
return;
}
var $this = $( this );
// Get the value.
var input = $this.val();
var input = input.replace(/[Ds._-]+/g, "");
input = input ? parseInt( input, 10 ) : 0;
$this.val( function() {
return ( input === 0 ) ? "" : input.toLocaleString( "en-US" );
} );
} );
/**
* ==================================
* When Form Submitted
* ==================================
*/
$form.on( "submit", function( event ) {
var $this = $( this );
var arr = $this.serializeArray();
for (var i = 0; i < arr.length; i++) {
arr[i].value = arr[i].value.replace(/[($)s._-]+/g, ''); // Sanitize the values.
};
console.log( arr );
event.preventDefault();
});
});
})(jQuery);
But I′m kind of missplaced here, is there any way to avoid such behavior so the field only allows numbers?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…