Dinesh M
Dinesh M

Reputation: 27

Retrieve value from a dynamically created textbox - jQuery

Fellas,

I am creating a text box dynamically, on a button click. User types a value in it. Now, how do I extract the value from the text box? I've tried with .keyup() and .change() but cant get it to work. Ive spent hours now. Is there any help out there?

The button html code -

<input type="button" value="Verify" id="addButton" class="verifybtn">

JQuery for creating the text box on the fly and then trying to read the value entered -

$(document).ready(function(){
var ctr=0;
$("#addButton").click(function () {

    if ( ctr < 1 ){
    $('.verifybtn').after('<div id="TextBoxDiv1"><label>Enter Verification Code : </label><input type="textbox" size=5 id="textbox1" class="textbox1"></div>');
id="textbox1" class="textbox1">');
    ctr++;
    }
});

$("#textbox1").keyup(function(){
    value = $("#textbox1").attr('value');   
    alert(value);
});

$("#textbox1").change(function() {
  alert('Handler for .change() called.');
});

});

If you can either quickly point out what Im doing wrong, or suggest alternative ways of achieving this, I shall be ever thankful.

-DM

Upvotes: 1

Views: 6722

Answers (3)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

You could also get it as:


$("#textbox1").live('keyup', function(){
    value = $("#textbox1").val();   
    alert(value);
});


Upvotes: 2

Deepak Kumar
Deepak Kumar

Reputation: 3751

Try this

 $(".textbox1").val();

Upvotes: 0

Mike Thomsen
Mike Thomsen

Reputation: 37526

$("#textbox1").val();

Gets the value. You can also rewrite the keyUp handler to look like this:

$("#textbox1").keyup(function(){
    var value = $(this).val();   
    alert(value);
});

Note the var keyword there. You want to make sure that the value variable is scoped to that function and only that function.

Upvotes: 1

Related Questions