I have problem in implementing regex for my field form.
User have to enter their phone number. In that field I use input type='text' because I want to limit the phone number user have entered to 11 digit only. That's why I'm using the input type='text'
$("#add_number").click(function() {
$("#phoneNumber").append(`<div >
<label for="add_owner"> Phone Number (more)</label>
<div >
<input type="text" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1');" maxlength="11" autocomplete="off">
</div>
</div>
`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<label for="add_owner"> Phone Number</label>
<div >
<input type="text" id="no_1" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1');" maxlength="11" autocomplete="off">
</div>
</div>
<div id="phoneNumber"></div>
<button id="add_number">Add Number</button>
It only enter the first number. How do I fix this ?
CodePudding user response:
Your regex gets mangled - it loses the \
It is not recommended to have inline handlers
here we delegate to the div and clone too.
const cleanPhone = function() {
this.value = this.value.replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1')
};
const $phoneDiv = $("#phoneNumber")
$phoneDiv.on("input", ".phone", cleanPhone)
$("#add_number").click(function() {
$phoneDiv.append($phoneDiv.find("div").eq(0).clone(true));
const $phones = $phoneDiv.find(".phone");
$phones.last()
.val("")
.attr("id",`no_${$phones.length}`)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="phoneNumber">
<div >
<label for="add_owner"> Phone Number</label>
<div >
<input id="no_1" type="text" maxlength="11" autocomplete="off">
</div>
</div>
</div>
<button id="add_number">Add Number</button>
CodePudding user response:
I think the problem is that you need to escape the backslash in the string:
.replace(/(\\..*)\./g,
$("#add_number").click(function() {
$("#phoneNumber").append(`<div >
<label for="add_owner"> Phone Number (more)</label>
<div >
<input type="text" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/(\\..*)\./g, '$1');" maxlength="11" autocomplete="off">
</div>
</div>
`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<label for="add_owner"> Phone Number</label>
<div >
<input type="text" id="no_1" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1');" maxlength="11" autocomplete="off">
</div>
</div>
<div id="phoneNumber"></div>
<button id="add_number">Add Number</button>
