Fokrule
Fokrule

Reputation: 854

jquery is not getting dynamically added input field id

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.

Upvotes: 1

Views: 169

Answers (3)

Johnathan Awma
Johnathan Awma

Reputation: 81

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.

Upvotes: 1

Wils
Wils

Reputation: 1231

 $(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.

Upvotes: 1

Sam Battat
Sam Battat

Reputation: 5745

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');
});

Upvotes: 2

Related Questions