0

I want to get the value of a text input. I would like to do this by using id and getElementById :

here HTML code :

<form>
  <fieldset>
  <legend>Input ordinate :</legend>
  <input type="text" id="ordinateId" name="input"/>
  <input type="button" id="startbuttonId" value="Start particle"/>
  </fieldset> 
</form>

and Javascript :

<script type="text/javascript"> 

var button = document.getElementById("startbuttonId");
var value = document.getElementById("ordinateId").value;

console.log(value);
button.onclick = function() {
  console.log(value);
}
</script>

but into the console, nothing appears for value. Where is the problem ?

Thanks

  • You need to access the input's value inside your function. It's setting the variable when the page loads before you've typed anything. – Interrobang Mar 06 '15 at 21:18
  • Where is this code being executed in relation to the form? – j08691 Mar 06 '15 at 21:22
  • I used the solution that you gave me but nothing appears in the console. I put javascript at the bottom of the html page. Where have I got to put it ? –  Mar 06 '15 at 21:30

3 Answers3

0

You need to get the value again when the event fires. Just move your var value

button.onclick = function() {
  var value = document.getElementById("ordinateId").value;
  console.log(value);
}
Adjit
  • 10,134
  • 12
  • 53
  • 98
0

The problem is that you are checking for the input's value before it is set(on document load). Just move the variable declaration within the click function like so:

var button = document.getElementById("startbuttonId");

button.onclick = function() {
  var value = document.getElementById("ordinateId").value;
  console.log(value);
}

JSFiddle

APAD1
  • 13,509
  • 8
  • 43
  • 72
  • your code works fine on JSFiddle but not on my server. could you tell me where to put the javascript code ? at the bottom or in section ? Thanks –  Mar 06 '15 at 21:44
  • Put it at the bottom, immediately before the closing body tag. That way you ensure that the element is rendered in the DOM before the JavaScript is executed. – APAD1 Mar 06 '15 at 21:47
  • ok, I pushed on return key once value typed instead of pushing on "start" button. How could I have the same behavior between pushing "return" and pushing on button. Thanks –  Mar 06 '15 at 21:51
  • You would have to set up a [keypress function](http://stackoverflow.com/questions/16089421/simplest-way-to-detect-keypresses-in-javascript) to check if enter is pressed and then fire the function. – APAD1 Mar 06 '15 at 21:53
0

With your current script you are assigning value only once, which I am assuming is an empty string. You need to put the assignment inside the function so it gets the current value of the input when it is clicked.

<script type="text/javascript"> 

var button = document.getElementById("startbuttonId");


button.onclick = function() {
    var value = document.getElementById("ordinateId").value;
    console.log(value);
}
</script>