Sergey Dubovik
Sergey Dubovik

Reputation: 165

jQuery not working for dynamically created input field

I have script, that on press of Enter on keyboard hides $this input and generates span with value of that field to display.

    $('.work_experience .achievements').on('keypress','input', function(event){
    if (!$(this).val() && event.which == 13 ) {
        alert('Input something');
        event.preventDefault();
    }
    else if (event.which == 13) {
        event.preventDefault();
        var value = $(this).val();
        $(this).parent().append('<span><i class="fa fa-times"></i> ' + value + '</span><input type="text" class="form-control input-xs" placeholder="I did" autofocus>');
        $(this).css('display', 'none');
        $('.achievements input:last-child').focus();
    }
});

It works. But then I have button, clicking on which generates new input field. And on that, newly created input, script doesn't work anymore. Help is appreciated.

PS Script adding new set of fields

    $('.form_fields').on('click','#add_work', function(event){
    event.preventDefault();
    var field_set = '<div class="form-group work_experience">'+                            
                    '<input type="text" class="form-control input-m" id="company_name" placeholder="Company name">'+
                    '<input type="text" class="form-control input-m" id="company_place" placeholder="Company location">'+
                    '<input type="text" class="form-control input-m" id="work_period_start" placeholder="Beginnig">'+
                    '<input type="text" class="form-control input-m" id="work_period_end" placeholder="End">'+
                    '<label><input type="checkbox"> Currently</label>'+
                    '<textarea class="form-control" rows="5" placeholder="Write a few sentences about that company"></textarea>'+
                    '<input type="text" class="form-control input-m" placeholder="Your position">'+
                    '<label><strong>Achievements</strong></label>'+
                    '<div class="achievements">'+
                    '<input type="text" class="form-control input-xs" placeholder="I did">'+
                    '</div>'+
                '</div>';
    $(this).prev().after(field_set);
});

Upvotes: 2

Views: 1652

Answers (2)

Balachandran
Balachandran

Reputation: 9637

Use event delegation for dynamically created dom

 $(document).on('keypress','input','.form-control',function(e){

     e.stopPropagation(); // stop the bubbling  if it is there 
     alert("cal");
    // do your work

    });

Note : you were created dom element is div <div class="form-group work_experience">'+ ,it is not input field

Upvotes: 2

sarath
sarath

Reputation: 56

try change from

$('.work_experience .achievements').on('keypress','input', function(event)

to

$('.work_experience .achievements').live('keypress','input', function(event)

Upvotes: 0

Related Questions