Joie Joie - 5 months ago 9
HTML Question

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?


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

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

JavaScript (jQuery)

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

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.


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