Search code examples
jquerymask

Add input with jquery mask


Hello guys I have this script below that is adding input, but I'm not able to insert the masks. The plugin I'm using https://github.com/igorescobar/jQuery-Mask-Plugin

In the first field the mask is running, when adding it is not adding the mask.

Could help?

<script type="text/javascript">
$(document).ready(function() {
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
            $(wrapper).append("<div><input type=\"text\" name=\"mytext[]\" id=\"date\"/><a href=\"#\" class=\"remove_field\">Remove</a></div>");
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove();
    })
});    
</script>

<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="mytext[]" id="date"></div>
</div>
<script type="text/javascript">
    $('#date').mask('00/00/0000');
</script>

Solution

  • First of all change id selector #date class .date because you can't have more than one element with the same id.

    Second thing you need to move the $('.date').mask('00/00/0000'); inside the $(document).ready(function() {}) method.

    Third thing, you have to bind mask to the newly created an input element. Below is the copy of your working code after the amending the above suggested changes.

        <script type="text/javascript">
        $(document).ready(function () {
            var wrapper = $(".input_fields_wrap"); //Fields wrapper
            var add_button = $(".add_field_button"); //Add button ID
            $(add_button).click(function (e) { //on add input button click
                e.preventDefault();
                $(wrapper).append("<div><input type=\"text\" name=\"mytext[]\" class=\"date\"/><a href=\"#\" class=\"remove_field\">Remove</a></div>");
                $('.date').mask('00/00/0000');
            });
    
            $(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
                e.preventDefault();
                $(this).parent('div').remove();
            })
            $('.date').mask('00/00/0000');
        });
    </script>
    
    <div class="input_fields_wrap">
        <button class="add_field_button">Add More Fields</button>
        <div><input type="text" name="mytext[]" class="date"></div>
    </div>
    <script type="text/javascript">
        $('#date').mask('00/00/0000');
    </script>