Hi! I am trying to enforce format of 2nd input field on first input field. For example if Pakistan is selected from first field, then format of second field should be 82201-11850546-1 and if other selected from first field, then digit only should be format of 2nd input field. every thing working fine till this point but then issue is when Pakistan is selected than I want two dashes 82201-11850546-1 should insert automatically in input field . below is my complete code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mobile Number Format Example</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<form id="myForm">
<label for="country">Country:</label>
<select id="country" onchange="updateMobileNumberFormat()">
<option value="others">Select Country</option>
<option value="pakistan">Pakistan</option>
<option value="other">Other</option>
</select>
<br><br>
<label for="mobile">Mobile Number:</label>
<input type="text" id="mobile" pattern="[0-9]{5}-[0-9]{7}-[0-9]" required />
<span class="error" id="mobileError"></span>
<br><br>
<input type="submit" value="Submit">
</form>
<script>
function updateMobileNumberFormat() {
var countrySelect = document.getElementById("country");
var mobileInput = document.getElementById("mobile");
var mobileError = document.getElementById("mobileError");
var countryValue = countrySelect.value.trim().toLowerCase();
if (countryValue === "pakistan") {
// Format for Pakistan: 82203-1185054-5
mobileInput.value = "";
mobileInput.placeholder = "82203-1185054-5";
} else {
// For other countries: plain digits, no dashes
mobileInput.value = "";
mobileInput.placeholder = "Digits only";
}
mobileInput.removeAttribute("pattern");
mobileInput.removeAttribute("title");
mobileError.textContent = "";
}
document.getElementById("myForm").addEventListener("submit", function(event) {
var countrySelect = document.getElementById("country");
var mobileInput = document.getElementById("mobile");
var countryValue = countrySelect.value.trim().toLowerCase();
if (countryValue === "pakistan") {
// Check if the mobile number matches the format for Pakistan
var pattern = /^(\d{5}-\d{7}-\d)$/;
if (!pattern.test(mobileInput.value.trim())) {
event.preventDefault(); // Prevent form submission
document.getElementById("mobileError").textContent = "Invalid format for Pakistan (e.g., 82203-1185054-5)";
}
} else {
// For other countries: just validate it's digits
var pattern = /^\d+$/;
if (!pattern.test(mobileInput.value.trim())) {
event.preventDefault(); // Prevent form submission
document.getElementById("mobileError").textContent = "Mobile number must be digits only";
}
}
});
</script>
</body>
</html>