Joie
Joie

Reputation: 141

Set variable to input value (jQuery)

So, I have the following code, and it's not working, and I'm not sure why. Any suggestions?

HTML:

<input type="number" placeholder="#" id="lineSpace"/>

<br/><br/><button id="go">update text!</button>

JavaScript (jQuery)

$(document).ready(function() {
var lineSpace = $("#lineSpace").val();

$("#go").click(function(){
alert("LINE SPACE: "+lineSpace+"");
});

This was a test to see if my variable was being gathered, but it seems not. The alert appears but simply says "LINE SPACE: ", without placing the variable after it. When I define the like this var lineSpace = "random number";(which is no use to me, as I need a value that is entered from the user-side), however, it works fine.

Upvotes: 0

Views: 1306

Answers (1)

theharls
theharls

Reputation: 163

Because you are assigning lineSpace when the page loads, and it's obviously blank then.

Move var lineSpace = $("#lineSpace").val(); into your click handler (above the alert() function call).

Upvotes: 1

Related Questions