我需要一个以数字 9 开头的文本框,我该怎么做?文本框只接受数字,但我需要它以数字 9 开头。我已经尝试过这样但它不起作用。
$(document).ready(function () {
var $phone = $("#phone");
$phone.mask('900000000', {reverse: false});
});
我需要一个以数字 9 开头的文本框,我该怎么做?文本框只接受数字,但我需要它以数字 9 开头。我已经尝试过这样但它不起作用。
$(document).ready(function () {
var $phone = $("#phone");
$phone.mask('900000000', {reverse: false});
});
$(function(){
//get the input element to const
const $phn = $('#phone');
//add keydown event
//if value is a length of 1 and code is backspace or delete return false
//if length is longer than 1 and delete key is pressed, reset to just 9
$phn.on('keydown', function(e){
const code = e.which || e.keyCode;
//keycode 8 = backspace, keycode 46 = delete
if($phn.val().length === 1 && (code === 8 || code === 46)){
return false;
}
else if(code === 46){
$phn.val('9');
placeCursor($phn);
}
});
//initialize value to 9 and place cursor
$phn.val('9');
placeCursor($phn);
//function to focus and place cursor in input box
function placeCursor(input){
$(input)[0].focus();
$(input)[0].setSelectionRange($(input).val().length, $(input).val().length);
}
});
<input type="text" id="phone" />
<script
src="https://code.jquery.com/jquery-3.6.0.slim.min.js"
integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI="
crossorigin="anonymous"></script>