randydalton411
randydalton411

Reputation: 117

Retrieving a value in jquery

var $form = $(' <form id="login"> </form> ');
$form.append('<label id="datakeylbl" for="datakey"> Enter Datakey');
$form.append('<input type="text" name="datakey" id="datakey"/>');
$form.append('<input type="submit" value="Login In" />');
$("#main").append($form);

var data = $("#datakey").val();

Unsure of why data does not get the value of the text in the datakey textfield.

Upvotes: 0

Views: 51

Answers (4)

Robert Messerle
Robert Messerle

Reputation: 3032

I updated your code and it works fine:

var $form = $('<form id="login"/>').append(
    '<label id="datakeylbl" for="datakey">Enter Datakey</label>',
    '<input type="type" name="datakey" id="datakey"/>',
    '<input type="submit" value="Login"/>'
).appendTo('#main').on('submit', function (event) {
    //-- prevent the form from submitting
    event.preventDefault();
    //-- grab the data from the text field
    var data = $("#datakey").val();
    //-- alert the data for troubleshooting
    alert(data);
});

I made the following changes:

  1. I merged the code into a single append() call, rather than multiple calls.
  2. I added your data code into a submit event.

Upvotes: 0

FlavioEscobar
FlavioEscobar

Reputation: 877

If your code is exactly how you posted, you are appending the form and immediately getting the field val. That way the field will be empty.

Can you try this code below? I made small changes and it is showing the "datakey" value only when the "Login In" is hit:

var $form = $(' <form id="login"> </form> ');
$form.append('<label id="datakeylbl" for="datakey"> Enter Datakey');
$form.append('<input type="text" name="datakey" id="datakey"/>');
$form.append('<input type="submit" id="login-button" value="Login In" />');
$("#main-form").append($form);

$('#login-button').click( function()
{
    var data = $("#datakey").val();
    alert( data );
    return false;
});

Maybe if you provide more details I can help you more.

Upvotes: 0

Timur
Timur

Reputation: 639

Try something like this

var data = "";

$( "#datakey" ).keyup(function() {
  data = $(this).val();
});

Upvotes: 0

Susheel Singh
Susheel Singh

Reputation: 3854

data value would be empty on load. you should try something like this to get the value.

JsFiddle:

http://jsfiddle.net/G5ezv/

var $form = $(' <form id="login"> </form> ');
$form.append('<label id="datakeylbl" for="datakey"> Enter Datakey');
$form.append('<input type="text" name="datakey" id="datakey"/>');
$form.append('<input type="submit" value="Login In" />');
$("#main").append($form);

$("#login").on("submit",function(){
    var data = $("#datakey").val();    
    console.log(data);
});

Upvotes: 1

Related Questions