简体   繁体   中英

Only allow specific numbers in text field

I have a script with a HTML form with a text field inside, right now this text field allows only numbers.

Although I would like to have the text field only allow numbers, and only allow the current value of a variable +1. For example, say the current value of the variable(currentValue) is 1 then the only number you can put into the text field is 2.

Here is the code I have so far:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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