Val Do
Val Do

Reputation: 2695

alert from input tag

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

Answers (6)

Sarath
Sarath

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

Piyush Arora
Piyush Arora

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

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);
});

Demo Fiddle

Upvotes: 0

user229044
user229044

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

Adil
Adil

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.

Live Demo

$(".submit").click(function(){
        var username = $(".login").val();
    var password = $(".password").val();
         alert(username);
});

Upvotes: 2

Sridhar Narasimhan
Sridhar Narasimhan

Reputation: 2653

Use the below script with user name within click function

$(".submit").click(function(){
var username = $(".login").val();
alert(username);
});

Upvotes: 2

Related Questions