I am very new to the UI part, i have one form which contains input type as number that field should accept only 10 digits only once the condition match i want to enable the submit button can you please help me did i miss anything ?
$(document).ready(function() {
$('#pnum').on('keypress', function(e) {
var $this = $(this);
var regex = new RegExp("^[0-9\b] $");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
// for 10 digit number only
if ($this.val().length > 9) {
e.preventDefault();
return false;
}
if (e.charCode < 54 && e.charCode > 47) {
if ($this.val().length == 0) {
e.preventDefault();
return false;
} else {
return true;
}
}
if (regex.test(str)) {
$('#submitButton').prop('disabled', false);
return true;
}
e.preventDefault();
return false;
});
});
<!-- CSS only -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI N" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<label for="exampleInputEmail3">Phone Number</label>
<div >
<div >
<span > 91</span>
</div>
<input type="number" id="pnum" name="phone_number" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" maxlength="10" required>
</div>
</div>
<input type="submit" name="submit" disabled id="submitButton" value="Submit" >
CodePudding user response:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<label for="exampleInputEmail3">Phone Number</label>
<div >
<div >
<span > 91</span>
</div>
<input type="number" id="pnum" name="phone_number" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" maxlength="10" required>
</div>
</div>
<input type="submit" name="submit" disabled id="submitButton" value="Submit" >
<script>
$(document).ready(function() {
$('#pnum').on('keypress', function(e) {
const value = e.target.value
var $this = $(this);
var regex = new RegExp("[0-9]{9}");
// for 10 digit number only
if (value.length > 9) {
e.preventDefault();
return false;
}
if (regex.test(value)) {
$('#submitButton').prop('disabled', false);
return true;
}
});
});
</script>
CodePudding user response:
for disable and enable based on string length if its 10 than
$(document).ready(function() {
$('#submitButton').prop('disabled', true);
$('#pnum').on('keypress', function(e) {
var $this = $(this);
if ($this.val().length == 10) {
$('#submitButton').prop('disabled', false);
}else{
$('#submitButton').prop('disabled', true);
}
});
});