0

I am trying to add a phone number mask using jquery. I am having an issue with the hidden phone number fields that get added after user asks for more phone number fields.

  $(".phone").on('input', function (e) {
    var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
    e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});

am not really sure why its not applying the on 'input' function to the rest of fields in the same class.

This is what my HTML looks like:

            <div class="form-group">
                <div>
                    <div class="input-group control-group after-add-more">
                        <input asp-for="PhoneNumber" type="text" name="addmore[]" id="phone" class="form-control k-textbox phone" placeholder="Enter Phone No.">
                        <div class="input-group-btn">
                            <button class="btn btn-success add-more" type="button"><i class="glyphicon glyphicon-plus"></i></button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="copy hide">
                <div class="control-group input-group" style="margin-top:10px">
                    <input asp-for="PhoneNumber" type="text" name="addmore[]" id="phone" class="form-control k-textbox phone" placeholder="Enter Other Phone No.">
                    <div class="input-group-btn">
                        <button class="btn btn-danger remove" type="button"><i class="glyphicon glyphicon-remove"></i></button>
                    </div>
                </div>
            </div>

Here is the full script incase it helps to narrow it down:

$(".phone").on('input', function (e) {
    var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
    e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});

$(document).ready(function () {
    $(".add-more").click(function () {
        var html = $(".copy").html();
        $(".after-add-more").after(html);
        
    });
});
$("body").on("click", ".remove", function () {
    $(this).parents(".control-group").remove();
});
tachidow
  • 53
  • 5

1 Answers1

0

Try targeting your newly created phone elements this way,

$(document).on("input", ".phone", function() { ... })

The elements you are creating do not exist when the DOM renders so you Event Handler will not work. Querying the document directly will allow you to use event handlers on the spontaneously created elements.

Here is a pen with a quick mockup. https://codepen.io/mujakovic/pen/QWpJabL

Vladimir Mujakovic
  • 650
  • 1
  • 7
  • 21