1

In my project I use Bootstrap 4 and jQuery / JavaScript.

I have this code:

$(document).ready(function () {
    $('.currencyMask').mask("###0.00", {reverse: true});
    $('.numbersMask').mask("#", {reverse: true});
});

function getDynamicInput(productType) {
    $(".dynamic-content-input").load("{{ route('product.product.feature') }}/" +
                                         productType +
                                         "/@if (!empty($product)){{ $product->id }} @else{{0}} @endif",
                                     function (response, status, xhr) {
    });
}

This code in result dynamic input:

<div class="dynamic-content-input">
    <div class="form-group row">
        <label class="col-form-label text-right col-lg-3 col-sm-12">Pole liczbowe</label>
        <div class="col-lg-9 col-md-9 col-sm-12">
            <input type="text" name="form-2" class="form-control  numbersMask " value="">
        </div>
    </div>
    <div class="form-group row">
        <label class="col-form-label text-right col-lg-3 col-sm-12">Pole tekstowe</label>
        <div class="col-lg-9 col-md-9 col-sm-12">
            <input type="text" name="form-3" class="form-control " value="">
        </div>
    </div>
</div>

This work fine. Problem is with the JavaScript function numbersMask.

When I add input in HTML - it's working fine (the function allows you to enter only numbers).

However, for input dynamically added, it does not work at all.

How can I repair it?

0

1 Answer 1

4

Change your code .mask code to this below. It should work for your dynamic inputs as well.

The reason it's not working is that when the DOM is loaded those dynamic inputs are not available to be masked with your requirements.

So in this case we need to use event binding in jQuery and use the jQuery .on method. The way it works is that it checks the whole document and applies your .mask to you input, including dynamically loaded inputs.

In your case, we will just need call the mask when you click or focus on the elements.

$(document).on("focus", ".currencyMask", function() {
  $(this).mask("###0.00", {
    reverse: true
  });
});

$(document).on("focus", ".numbersMask", function() {
  $(this).mask("#", {
    reverse: true
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.