Bruno
Bruno

Reputation: 1055

Use maskMoney in input that is created dynamic

In the form that opens by default the function in js works well. But then in the form I have the possibility to create more fields dynamically, but in those fields that you create dynamically it doesn't work.

Let me explain.

Code:

$(document).ready(function() {
  var max_fields = 10; //maximum input boxes allowed
  var wrapper = $(".input_fields_wrap"); //Fields wrapper
  var add_button = $(".add_field_button"); //Add button ID

  var x = 1; //initlal text box count
  $(add_button).click(function(e) { //on add input button click
    e.preventDefault();
    var length = wrapper.find("input:text").length;

    if (x < max_fields) { //max input box allowed
      x++; //text box increment
      
     $(wrapper).append('<div id="teste"><div class="form-group col-md-2"><input type="text" class="form-control1 Preco" name="Valor[]" value="0.00" /><span class="form-highlight">$</span><span class="form-bar"></span><label class="label1" for="Valor">Valor</label></div><button class="remove_field" style="background-color: #313348;"><span class="fa fa-trash fa-fw" aria-hidden="true"></span></button></div>');
      }
  });

  $(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
    e.preventDefault();
    $("#teste").remove();
    x--;
  })
});



$(function() {
  $('.Preco').maskMoney({ decimal: '.', thousands: ' ', precision: 2 });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>

<button class="btn btn-warning caixa add_field_button" style="float:right;"><i class="fa fa-plus-square fa-5x taman" aria-hidden="true"></i></button>

<div class="input_fields_wrap">
     <div class="form-group col-md-2">                      
      <input type="text" class="form-control1 Preco" name="Valor[]" value="0.00" required>
       <span class="form-highlight">$</span>                        
       <span class="form-bar"></span>                       
       <label class="label1" for="Valor">Valor</label>        
     </div>
    </div>

As I show in the example the first input works correctly, but when I create a dynamic input it lets the maskMoney function work

Upvotes: 0

Views: 507

Answers (1)

Ouroborus
Ouroborus

Reputation: 16875

$(document).ready(function() { and $(function() { are the same thing. (This is mentioned in the jQuery documentation for .ready()) Because of that, you've essentially declared two onready handlers. onready handlers can happen in any order.

Combine them into one onready handler and order the contents such that the call to maskMoney happens last.

Upvotes: 1

Related Questions