Is there a way to let the user type only three cha开发者_开发技巧racters? For example, I want to only allow 3
, 6
or 9
in an input text field.
Here's a way to do it using jQuery: http://jsfiddle.net/ThiefMaster/UZJn2/
<input type="text" maxlength="1" class="only369" />
$('.only369').keyup(function(e) {
if(this.value != '3' && this.value != '6' && this.value != '9') {
this.value = '';
}
});
A pure JS solution:
http://jsfiddle.net/ampersand/eg8Dn/
source:
<input id="number" type="number" min="3" max="9" step="3" value="3">
<script>
document.getElementById('number').addEventListener('keyup',function(ev){
this.value=!!~['3','6','9'].indexOf(this.value) ? this.value : '';
})
</script>
I think it might help you...
<script type="text/javascript">
function validate(e)
{
return (e.charCode == 51 || e.charCode == 54 || e.charCode == 57)
}
</script>
<form>
<input name="name" type="text" onkeypress="return validate(event);" />
</form>
If you want to limit the number of occurences, just set the maxlength property of the input field.
Of course. Listen for the onchange
event on the input element and when the value is different from those three numbers and greater than tree, return false
.
Short answer:
"0123456789".replace(/[^369]/g, "")
Use this plugin. It is FANTASTIC : Alphanumeric
Answer of your question is as simple as this
$('.numericInput').numeric({ichars:'0124578'});
From authors side:
Did you ever have the need to prevent users from entering certain characters into your form?
Looking at the plugins available at jQuery, I found a great plugin made by Sam Collet called Numeric.
But it was too limited, what if I'm asking the user to create a username? Or what if I need to enter a number with decimals or an IP Address? There is another great plugin called Masked Input by Josh Bush, which can also control user input by defining a mask. The problem however with that was the length of text to be inserted must be defined as well. Again, what if I needed to control input of a username? I can't tell how many characters the user will be using, and I can't force him to use just 8 characters ,so I created AlphaNumeric.
jQuery AlphaNumeric is a javascript control plugin that allows you to limit what characters a user can enter on textboxes or textareas. Have fun.
Use onchange="this.value=this.value.replace(/[^369]/g, '')"
精彩评论