I have an input:
And I don\'t have
Is there any reason you are avoiding using a drop down select
tag?
This will give the user a very limited choice of numbers (set to your preference).
You could even populate the <option>
fields with numbers 1 through 100 (or whatever you choose) using PHP or JavaScript so you didn't have to manually type each number in the HTML code.
<select>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
Try it dude, my problem was solved
var prevVal = 0;
$("input[type=number]").on("keydown", function(e){
prevVal = Number($(this).val());
});
$("input[type=number]").on("keyup", function(e){
var minVal = $(this).attr("min");
var maxVal = $(this).attr("max");
var step= $(this).attr("step");
var currentVal = $(this).val();
if(!(currentVal>=1)){
$(this).val(1)
}
});
The user is expected to be able to type in the field, as one option. Although it is possible to prevent this in part (namely when JavaScript is enabled and event handlers in your code cover the ways that the user might use), there is no point in using the element when you specifically do not want to get its basic functionality.
If you only want to allow the two values 4 and 6, as it seems from your example, and you want to prevent the user from simply typing one of them, then you should use a select
element or a set of two radio buttons.
Although I am not sure as to what the step attribute does but pretty sure that you can find a way to use it as per your requirements in below code
The Code below makes sure that the allowed values are between min and max attribute specified only The Code is using jquery 1.10 onwards.
var prevVal = 0;
$("input[type=number]").on("keydown", function(e){
prevVal = Number($(this).val());
});
$("input[type=number]").on("keyup", function(e){
var minVal = $(this).attr("min");
var maxVal = $(this).attr("max");
var step= $(this).attr("step");
var currentVal = $(this).val();
if(!(currentVal<=maxVal&¤tVal>=minVal)){
$(this).val(prevVal)
}
});
Edited to block copy/paste:
<script type="text/javascript">
document.getElementById('amount').onkeypress = function(e) { e.preventDefault(); };
document.getElementById('amount').onkeydown = function(e) {
if(e.keyCode != 38 && e.keyCode != 40)
e.preventDefault();
};
if(document.addEventListener)
document.getElementById('amount').addEventListener('contextmenu',function(e) { e.preventDefault();
},false);
</script>
http://jsfiddle.net/Wh5Ms/2/
Then you could add a <noscript>
tag for users with JavaScript turned off and show them a <select>
element, etc.