Reputation: 2695
Hi all I have this script
<form id="logform">
<input class="login" name="login" type="text"><br />
<input class="password" name="password" type="password"><br />
<input class="submit" type="submit" value="login">
</form>
var username = $(".login").val();
var password = $(".password").val();
$(".submit").click(function() {
alert(username);
});
and when I type text in input and click submit alert is empty ?
Upvotes: 2
Views: 1276
Reputation: 608
You have taken the value before the submit click thats the issue
put the following codes inside the click function and try var username = $(".login").val(); var password = $(".password").val();
<form id="logform">
<input class="login" name="login" type="text"><br />
<input class="password" name="password" type="password"><br />
<input class="submit" type="submit" value="login">
</form>
$(".submit").click(function(){
var username = $(".login").val();
var password = $(".password").val();
alert(username);
});
Upvotes: 0
Reputation: 138
Modify your code to assign value after submit:
$(".submit").click(function(){
var username = $(".login").val();
var password = $(".password").val();
alert(username);
});
Because, value are being assigned when page is called. That is why username is empty.
Upvotes: 4
Reputation: 9947
the value of username get initialized on load so it will be always empty
$(".submit").click(function(){
alert($(".login").val()); //get the current value
});
or
$(".submit").click(function(){
var username = $(".login").val();
alert(username);
});
Upvotes: 0
Reputation: 239291
You need to get the username/password inside the submit
callback. The way you're code is written now, you're getting the username/password immediately, when they're still blank, and never getting the again.
Upvotes: 2
Reputation: 148120
You are getting the user name before the click
event is fired on document load
, put in click event to get the value of username when click
is triggered.
$(".submit").click(function(){
var username = $(".login").val();
var password = $(".password").val();
alert(username);
});
Upvotes: 2
Reputation: 2653
Use the below script with user name within click function
$(".submit").click(function(){
var username = $(".login").val();
alert(username);
});
Upvotes: 2