Reputation: 117
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
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:
append()
call, rather than multiple calls.data
code into a submit
event.Upvotes: 0
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
Reputation: 639
Try something like this
var data = "";
$( "#datakey" ).keyup(function() {
data = $(this).val();
});
Upvotes: 0
Reputation: 3854
data value would be empty on load. you should try something like this to get the value.
JsFiddle:
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