2015-04-04 2 views
3

У меня есть сценарий с формой 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; 
+0

и в чем проблема сейчас? – Legends

+0

Мой вопрос в том, как я допускаю только значение, равное значению переменной + 1, теперь оно позволяет все числа. – Fulgut98

ответ

3
<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> 
+0

Я только что проверил ваш код, он не работает, но спасибо за предложение. – Fulgut98

+0

Я обновил свой ответ и включил jsfiddle. currentValue установлен в 2, и он не позволяет вводить что-либо, кроме 3. – brianjob

+0

Я ценю усилия, он работает только для firefox, который является проблемой, я тестировал его как на firefox, opera, так и на google chrome. – Fulgut98