javascript - 仅允许文本字段中的特定数字

标签 javascript html forms post textfield

我有一个带有 HTML 表单的脚本,里面有一个文本字段,现在这个文本字段只允许数字。

虽然我希望文本域只允许数字,并且只允许变量的当前值+1。 例如,假设变量 (currentValue) 的当前值为 1,那么您可以在文本字段中输入的唯一数字是 2。

这是我目前的代码:

HTML:

<form id="value-form" action="value.php" method="POST" name="value-form">
<input onkeypress="return isNumberKey(event)" type="text" name="amount" id="amount" /> <!-- This is the text field I would like to only allow the value+1 -->
<input type="image"  src="Button1.png" id="customButton" value="submit" alt="but"/>
</form>

Javascript:

function isNumberKey(evt) //This is the function I use to only allow numbers in the text field
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;

return true;
}

var request = new XMLHttpRequest();
request.open('GET', 'currentValueFile.txt', false);
request.send();

var currentValue = request.responseText //this is the variable value I want to only allow +1 in the text field
document.getElementById("currentValue").innerHTML = currentValue;

最佳答案

<form id="value-form" action="value.php" method="POST" name="value-form">
<input onkeypress="return isNumberKey(event)" type="text" name="amount" id="amount" /> <!-- This is the text field I would like to only allow the value+1 -->
<input type="image"  src="Button1.png" id="customButton" value="submit" alt="but"/>
</form>

<script type="text/javascript">
function toDec(code) {
  return code - 48;
}
function isNumberKey(evt) //This is the function I use to only allow numbers in the text field
{
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57 || toDec(charCode) != currentValue + 1))
      return false;

    return true;
}

</script>

<script type="text/javascript"> 
var request = new XMLHttpRequest();
request.open('GET', 'currentValueFile.txt', false);
request.send();

var currentValue = parseInt(request.responseText) //this is the variable value I want to only allow +1 in the text field

</script>

关于javascript - 仅允许文本字段中的特定数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29451856/

相关文章:

javascript - 如何找到文本容器中最后一个可见单词的位置?

javascript过滤器编辑并保存数组

html - 使用jquery mobile为iOS设置phonegap

javascript - dojo/on 事件类型列表?

javascript - Gatsby:单击路由中的 anchor 元素会导致重新渲染

javascript - 用于数据网格(或电子表格)的 HTML5 javascript 框架

html - content-editable 属性对 div 内容渲染的不正确影响

php - (php) 在初始表单后获取额外的输入?

php - 使用 php 向 mySQL 提交一个 html 表单

javascript - 根据上一行输入值使一些 TextArea 行可选/不可见