Reputation: 9212
I am creating a login form dynamically, using jQuery and AJAX response. Form is created and displaying properly. But, I'm not able to read the form data.
This is my code:
$(document).ready(function(){
$('#proper-form').on( 'click', '#submit-button', function() { // loginForm is submitted
alert ("here");
var username = $('#email').attr('value'); // get username
var password = $('#password').attr('value'); // get password
alert (password);
alert (username);
// code for form submit using ajax
});
});
It's alerting undefined undefined
for both username and password.
Can anyone help me in figuring out what's wrong here?
Upvotes: 4
Views: 58275
Reputation: 31
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#test").click(function(){
//textbox
var first_name = $("#first_name").val();
alert(first_name);
});
});
</script>
<div>username <input type="text" id="first_name" class="first_name" name="first_name" placeholder="type username"/>
<a href="javascript:void(0)" id="test" class="shortc-button small blue">Get Data</a></div>
For more details visit : http://www.codingprogrammer.com/tutorialdemo/jquery-tutorial/get-value-of-textbox-in-jquery-example/
Upvotes: 0
Reputation: 121998
Just use the val()
function, to get the value:
var username = $('#email').val();
var password = $('#password').val();
To set the value use val(value)
function:
$('#email').val('some new value');
Upvotes: 9
Reputation: 74
There are already good answers here, but I thought you should understand why using .attr() doesn't work, even though value is indeed an attribute of the input field.
When you use $('#email').attr('value');, this is equivalent to something like:
input.getAttribute('value'),
which would return "something" for:
<input type="text"value="something"/>
regardless of what the user typed in.
However, using
$('#email').val()
is equivalent to something like:
input.value
which would instead return whatever the user actually typed into the field.
In this case, you don't have a value="" implicitly set: you just want what the user typed in.
Therefore, use .val()
.
Upvotes: 0
Reputation: 388316
You need to use .val() to read the value of an input element, not attribute
var username = $('#email').val();
Upvotes: 2