"autoNumeric.js" not working in dynamically created form element

834 views Asked by At

I'm using AutoNumeric.js (v4.6.0) in my project and I have a form that dynamically creates a price field. When the page is loaded, the first input that comes by default works fine, but the ones that are created automatically afterwards do not work unfortunately. How can i solve this problem ? Thank you from now.

$(function () {
        new AutoNumeric(".autonumber", { currencySymbol : '$' });

        $(document).on('click', '#addSpending', function () {
            var newSpending =
                '<div class="row g-1">' +
                    '<div class="col-md-12">' +
                        '<input type="text" class="form-control autonumber" name="amount[]" required>' +
                    '</div>' +
                '</div>';

            $('#spendings').append(newSpending);
        });
    });
2

There are 2 answers

0
zb22 On

You need to use the AutoNumeric instance after you append the field to the form like so:

$(function () {
  $(document).on("click", "#addSpending", function () {
    var newSpending =
      '<div class="row g-1">' +
      '<div class="col-md-12">' +
      '<input type="text" class="form-control autonumber" name="amount" required>' +
      "</div>" +
      "</div>";

    $("#spendings").append(newSpending);
    new AutoNumeric("input[name=amount]", {
      currencySymbol: "$"
    })
  });
});

Here's also a sandbox

1
Faisal Burhanuddin On

put inside your looping bro sist this code $('.auto').autoNumeric('init');

<script type="text/javascript">
jQuery(function($) {
    $('.auto').autoNumeric('init');
});
$(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();
        if(x < max_fields){ //max input box allowed
      var newSpending = '<input type="text" class="form-control col-4 mr-2 auto text-right" name="topamount[]""/>';
            x++; //text box increment
            $(wrapper).append(newSpending); //add input box
      jQuery(function($) {
          $('.auto').autoNumeric('init');
      });
        }
    });
    
    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});
</script>