简体   繁体   English

如何为输入字段设置默认值但可以更改?

[英]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. 我目前正在为我的Project Euler网站进行一些用户输入,并且希望每个问题都具有一个输入字段,该字段的默认值是网站上问题中的那一个,因此您可以按提交并获取答案,但我也希望它是可变的,以便您可以使用该函数查找任何限制数的答案。

 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 . 函数findSum在这里是我借助变量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. 我的问题是,如果我将HTML或JS中的value属性设置为f.ex“ 1000”,则它不再取决于输入。 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. 我曾考虑过使用占位符,但对于600851475143之类的数字或问题8中的荒谬数字,这是不现实的。

Greatly appreciate any help, have a nice day! 非常感谢您的帮助,祝您有美好的一天!

In order to set a default value for your input field you have to set the "value" attribute for that input, as follows. 为了为您的输入字段设置默认值,您必须为该输入设置“ value”属性,如下所示。 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. 接受输入值并将其放入js变量的方式是静态的,因此,一旦接受,就不会再对其进行更新。 In order to have always the fresh value, you have to take it inside the findSum function. 为了始终新鲜参数,你必须把它的findSum函数 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. 我不知道您想在findSum函数中做什么,所以我只是在结果框中回显提交的值。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM