0

Please how do I effect a keyup event on an input field I added to an HTML page through JavaScript on button click?
Here is my user interface:
The Input here accepts only numbers and formats the number using commas and decimal points
If I click on 'Add Other Fees' button it adds another field where I can enter the fee name and amount(see UI below):
UI with Fee name and Amount
But the amount field does not behave like the other amount fields on the page even when they have the same input field attributes. Please what's the problem and how can I solve it?
Here is my javascript to add other

fees:<br>`$("#addButton").on("click",function(){
            // let newElem = elemToAdd();
            $('#fees').append("<div class='col-sm-6'>"+
                "<span class='remove-item-form fa fa-times color-danger' style='cursor:pointer;right: 0;margin-right: 50px;font-weight: bolder;'></span>"+
                "<div class='row'>"+
                    "<div class='col-sm-6'>"+
                        "<div class='form-group'>"+
                            "<label class='form-label'>Fee Name<span class='asterik'>*</span></label>"+
                            "<input type='text' name='fee_name[]' class='form-control text-capitalize'/>"+
                        "</div>"+
                    "</div>"+
                    "<div class='col-sm-6'>"+
                        "<div class='form-group'>"+
                            "<label class='form-label'>Amount<span class='asterik'>*</span></label>"+
                            "<input type='text' name='amount[]' class='form-control number'/>"+
                        "</div>"+
                    "</div>"+
                "</div>"+
            "</div>");
        });` <br> Here is my code for number formating:<br>`$('input.number').keyup(function(event) {
            // skip for arrow keys
            if(event.which >= 37 && event.which <= 40){
                event.preventDefault();
            }
            let returned_value = (index, value) => {
                return value
                .replace(/\D/g, "")
                .replace(/([0-9])([0-9]{2})$/, '$1.$2')  
                .replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ",");
            }
            $(this).val(returned_value);
        });`
Jesper Martinez
  • 611
  • 5
  • 15
  • 1
    Try this: put $('input.number').keyup in a function, than call the function inside the $("#addButton").on("click" at the end, after div creation – Luciano May 23 '20 at 13:11
  • Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – freedomn-m May 23 '20 at 14:29
  • Events such as `$("#id").click(` only apply to elements that exist at the time the code runs. You need to use event delegation `$(document).on("click", "#id", ...` – freedomn-m May 23 '20 at 14:31

0 Answers0