开发者

Allow only 3 numbers

I want to make a javascript (or jquery) function that works onChange and allow only to write 3 numbers : 5, 15 or 25

If the user write an other valu开发者_如何学编程e (example 3 or 4...), the input have to be reset to 0

How can I do that?


If you're going to limit the possible values that strictly, a <select> is by far the best way to do this.

<select>
    <option>5</option>
    <option>15</option>
    <option>25</option>
</select>

Works with JavaScript disabled. Completely browser compatible. Screen-reader friendly.


This should help, if you are using jQuery:

$('.myField').change(function() {
  var field = $(this);
  var values = new Array("5", "15", "25");

  $.inArray(field.val(), values) >= 0 ? /* Everything is ok */ : field.val("0");
});

I'm not sure if change() will give you strange performance issues. It if does, try blur().

Hope that helps.


you can accomplish that elegantly using the jQuery Validation plugin

http://docs.jquery.com/Plugins/validation

It has many features for automatic form validation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜