Maarty
Maarty

Reputation: 1190

How to get .val() value of texbox created by ajax

I have html textbox

 <input type="text" id="inputfilter" style="width: 230px;" /> 

I'm creating this input dynamically via AJAX .

How can I retrieve a value of this checkbox? I tried

$("#inputfilter").val() 

But didn't work because textbox was not created on page initialization but later via AJAX . I tried things like this

$("#inputfilter").live('val', function(e) {})

But it didn't work.

Thanks

Upvotes: 2

Views: 1137

Answers (2)

zs2020
zs2020

Reputation: 54543

If you use append() to create the control dynamically, then your approach should be fine. Try my test code on JSFIDDLE.

My test code simulates the ajax call and then set and retrieve the value, it works.

<div id="parentId"></div>

setTimeout(function () {
    $('#parentId').append('<input type="text" id="inputfilter" style="width: 230px;" />')
}, 2000);

setTimeout(function () {
    $('#inputfilter').val('test');
}, 3000);

setTimeout(function () {
    console.log($('#inputfilter').val());
}, 4000);

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96286

$("#inputfilter").val()

should work. The only reason I can think of it's not working is that you tried to retrieve the value before you created the element (and I assume here that you managed to create the element, with the correct id.. but hell, you never know).

Note: .live is for event handling like clicks, so it's not relevant here (but yes, with events that's one way to go).

Upvotes: 2

Related Questions