4

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?

trejder
  • 17,148
  • 27
  • 124
  • 216
Devesh Agrawal
  • 8,982
  • 16
  • 82
  • 131
  • possible duplicate of [How do I get the value of a textbox using jQuery?](http://stackoverflow.com/questions/463506/how-do-i-get-the-value-of-a-textbox-using-jquery) – senthilbp Sep 28 '13 at 07:31

4 Answers4

9

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'); 
trejder
  • 17,148
  • 27
  • 124
  • 216
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

You need to use .val() to read the value of an input element, not attribute

var username = $('#email').val();
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

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().

Uriah Sanders
  • 74
  • 1
  • 4
0
<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/