1

I have one input field by default in html form. If user want to add more they can add more input field. I have done this adding more input field feature by jquery. Now I want to get new added field id and validate those input field using jquery. But jquery is not getting those added id. here is my form normal input field

<td> <input readonly type="text" name="student_id[]" placeholder="{{ $details->batch_id }}" value="{{ $details->batch_id}}" class="form-control"> </td>

Now here is my dynamically adding input field code

var tr='<tr>'+
    '<td> <input type="text" name="student_id[]" class="form-control" id="addedstudent-id"> </td>'+
    '</tr>';

Here is my jquery code to get this newly added input field

 $('#addedstudent-id').focusout(function(){
        console.log('d');
    });

But it is not showing anything in console. Not even any error.

Mario
  • 4,784
  • 3
  • 34
  • 50
Fokrule
  • 844
  • 2
  • 11
  • 30
  • You should use [delegate event handler](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements/18144022#18144022). – Hikarunomemory Apr 11 '18 at 03:38
  • Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – 4b0 Apr 11 '18 at 03:43

3 Answers3

2

When creating an element dynamically, you need listen to the element using a parent static selector. e.g:

$('table').on('focusout', '#addedstudent-id', function() {
  //do something
  console.log('d');
});
Sam Battat
  • 5,725
  • 1
  • 20
  • 29
1

If you add elements dynamically, you MUST set handlers JUST AFTER YOU ADDED TO THE DOCUMENT.

E.g,

var tr='<tr>'+
'<td> <input type="text" name="student_id[]" class="form-control" id="addedstudent-id"> </td>'+
'</tr>';
//If you add handlers here, It will not work since element is not in the document, jquery will not find it.
$('#some-element').append(tr);

 $('#addedstudent-id').focusout(function(){
    console.log('d');
});

Should work, I used to face like this.

1
 $(document).on('focusout','#addedstudent-id',function() {
        console.log('d');
    });

you can use document to set the listener. So you can be certain the function will trigger no matter where you put the new element.

Wils
  • 1,178
  • 8
  • 24