javascriptjqueryhtmljquery-mask

Set jquery mask on a dynamically inserted input?


Set jquery mask on a dynamically inserted input?

I'm trying to do it in the down format, but I'm not succeeding.

The new input loses the mask.

Can someone help me with this please.?

<div class="control">
<input type="text" name="item_valor" placeholder="Valor" class="input valor" maxlength="255" id="id_item_valor">
</div>

.

 $(document).ready(function(){
        $('.valor').mask("#.##0,00", {reverse: true});
    });

.

$(document).on('click', '#addItem', function () {
var newElement = $('.control:last').clone(true);
$('.control:last').after(newElement);
})

Solution

  • set the mask on focus of the input like this

    $(document).on("focus", ".valor", function() { 
        $(this).mask("#.##0,00", {reverse: true});
      });
    

    you can probably remove it from document.ready function and also instead of cloning and appending in 2 lines you can shorten it to 1 line with this

    $('.control:last').after($('.control:last').clone());
    

    here is a working fiddle https://jsfiddle.net/tv7w3Lku/3/

    Side note: cloning an element with ID will create multiple elements with same ID which is probably not the best way, you should just stick with class in this case