简体   繁体   中英

.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?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM