Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 904
LandonWO Avatar asked Dec 07 '22 09:12

LandonWO


1 Answers

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);
});
like image 52
chris-mv Avatar answered Dec 21 '22 23:12

chris-mv