简体   繁体   中英

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);
})

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

Just recall your mask function after each input is added to the DOM.

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

I was having this same problem, and discovered the .masked() function will apply the mask to a dynamic value. Hope this helps:

HTML:

<input name="phone" type="text">

<button>insert dynamic value</button>

JS:

$(function(){
    $("input[name='phone']").mask("(000) 000-0000");
});

$("button").click(function(){
    newPhoneNumber = "1231231234";
    maskedValue = $("input[name='phone']").masked(newPhoneNumber));
    $("input[name='phone']").val(maskedValue);
});

fiddle: https://jsfiddle.net/qcsf3z0j/4/

and docs: https://igorescobar.github.io/jQuery-Mask-Plugin/docs.html#getting-a-masked-value-programmatically

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM