Html 将文本框值转换为 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19580447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting text box value to int
提问by krikara
I have been trying to apply solutions I found on both Google and Stackoverflow, but they don't seem to be working.
我一直在尝试应用我在 Google 和 Stackoverflow 上找到的解决方案,但它们似乎不起作用。
What exactly is going wrong here? The checkbox is insignificant here and I can take it out, but it makes no difference.
这里到底出了什么问题?复选框在这里无关紧要,我可以将其删除,但没有任何区别。
<div class="form-group">
<label for="tbid" class="col-lg-3 control-label">Results per page </label>
<div class="col-lg-3">
<input type="checkbox" class="checkbox" display="inline-block" name="checkbox_results" onclick="checkbox_results_click();">
<input type="text" id="results" class="form-control" name="results" placeholder="results">
</div>
</div>
Then in the js portion, I am trying to convert results into an int.
然后在 js 部分,我试图将结果转换为 int。
<script type="text/javascript">
int results = null;
var x=document.getElementById("results").value;
results = parseInt(x);
if(results==null)
results=10;
var pager = new Pager(results);
</script>
EDIT: I should also add that if I just put a int parameter when calling pager, like 25, for example, it actually works. So something is going wrong with results.
编辑:我还应该补充一点,如果我在调用寻呼机时只输入一个 int 参数,例如 25,它实际上可以工作。所以结果出了问题。
回答by Rishab Arya
Instead of using parseInt
use parseFloat
it will work like this
而不是使用parseInt
useparseFloat
它会像这样工作
results = parseFloat(x);
回答by Rishab Arya
Use parseFloat it will work like this
使用 parseFloat 它会像这样工作
<script type="text/javascript">
int results = null;
var x=document.getElementById("results").value;
results = parseFloat(x);
if(results==null)
results=10;
var pager = new Pager(results);
</script>
回答by Sudhir Bastakoti
there's no int
in js, you could do:
int
js中没有,你可以这样做:
var results;
var x=document.getElementById("results").value;
results = /^[\d]+$/.test(x);
if(!results)
results=10;
var pager = new Pager(results);
回答by aaronps
The trick is +(element.value), add || default_value in case is invalid, or nothing. Or add your own checks.
诀窍是 +(element.value),添加 || 如果 default_value 无效,或者什么都没有。或者添加您自己的检查。
<!DOCTYPE html>
<html><head><title>to int()</title>
<script type="text/javascript">
function doResults()
{
var element = document.getElementById('results'),
value = +(element.value) || 0;
// write back the value in case is invalid
element.value = value;
alert("The value is " + value);
}
</script></head>
<body>
<input type="text" id="results" class="form-control" name="results" placeholder="results">
<button onclick="doResults();">Check Results</button>
</body></html>