Jorgen
Jorgen

Reputation: 93

How can I set a default, but changeable, value to an input field?

I'm currently working on some user input for my Project Euler site, and want each problem to have an input field with the default value of the one thats in the question on the site, so that you can just press submit and get the answer, but I also want it to be changeable, so that you can use the function to find the answer for any limit number.

var problem1El = document.getElementById("problem1").value;
var problem1buttonEl = document.getElementById("problem1button");
problem1buttonEl.addEventListener("click", findSum);
<p>Problem 1</p><input type="text" id="problem1"><button id="problem1button">Submit</button><a href="https://projecteuler.net/problem=1" target="_blank" class="links">Problem</a><p id="answer1"></p>

The function findSum here is where i calculate the answer, with help of the variable problem1El. My problem is that if i set the value property in either HTML or JS to f.ex "1000", it doesn't change depending on the input anymore. So neither this:

input type="text" value="1000" id="problem1"

nor this:

var problem1El = document.getElementById("problem1").value = "1000";

allows me to give it a default value that is changeable. I've thought about using placeholders instead, but for numbers like 600851475143 or the ridiculous one in problem 8 that is just unrealistic.

Greatly appreciate any help, have a nice day!

Upvotes: 1

Views: 7864

Answers (1)

sirnino
sirnino

Reputation: 427

In order to set a default value for your input field you have to set the "value" attribute for that input, as follows. The way you take the input value and put it in your js variable is static so, once you took it, it won't be updated anymore. In order to have always the fresh value, you have to take it inside the findSum function. I don't know what do you want to do within the findSum function so I, simply, echo the submitted value in a result box.

var problem1El = document.getElementById("problem1");
document.getElementById("problem1button").addEventListener("click", findSum);

function findSum(){
  var v = problem1El.value;
  document.getElementById("result").innerHTML = v;
}
<input type="number" id="problem1" value="1000"/>
<button id="problem1button">Submit</button>

<p>Result is: <span id="result"></span></p>

Upvotes: 1

Related Questions