LandonWO
LandonWO

Reputation: 1279

.val() not getting updated value from input

I have two input fields, and I'm trying to get their values using jquery by clicking a button. It seems like a very simple operation, but for the life of me I can't get it to work. Here is the code snippet:

Name: <input type="text" id="name" value="test1"><br>
Message: <input type="text" id="line" value="test2"><br>
<button id="submitButton">Submit</button>

<script>
name1 = $("#name").val();
line1 = $("#line").val();

$("#submitButton").click(function(){
    alert("Name: " + name1 + "\nMessage: " + line1);
});

</script>   

If I don't specify the value, the alert returns with undefined for both variables. If I change the values of the input and click the button, it still says test1 and test2. There has to be something simple that I'm missing here, anyone know what it is?

Upvotes: 4

Views: 15440

Answers (5)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

As mentioned in other answers, the problem is that you are precomuting the variables and expecting them to magically change. However I would strongly suggest using Vanilla JS

document.getElementById('submitButton').onclick = function() {
    var name1 = document.getElementById('name').value,
        line1 = document.getElementById('line').value;
    alert("Name: " + name1 + "\nMessage: " + line1);
};

Upvotes: 2

nemmy
nemmy

Reputation: 751

You've set variable values outside of the click function. To the value is set on page load, not whenever you run the function. Try this:

Name: <input type="text" id="name" value="test1"><br>

Message:
Submit

$("#submitButton").click(function(){ name1 = $("#name").val(); line1 = $("#line").val(); alert("Name: " + name1 + "\nMessage: " + line1); });

Upvotes: 0

highwingers
highwingers

Reputation: 1669

you should wrap your code within document.ready() event...

$(document).ready(function() {  
name1 = $("#name").val();
line1 = $("#line").val();

$("#submitButton").click(function(){
    alert("Name: " + name1 + "\nMessage: " + line1);
});

// Handler for .ready() called.
});

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

name1 = $("#name").val()

creates a new string variable name1 that has the value of $("#name").val() as it is at the moment. .val() does not get called each time you try to access name1. The simplest thing to do would just be to use $("#name").val() instead.

http://jsfiddle.net/wTvku/

Upvotes: 2

chris-mv
chris-mv

Reputation: 261

In your code, you fetch the values when the script is initialized, and then reference the value they had at that point in your click function rather than fetching the current value.

Try:

$("#submitButton").click(function(){
    name1 = $("#name").val();
    line1 = $("#line").val();
    alert("Name: " + name1 + "\nMessage: " + line1);
});

Upvotes: 12

Related Questions