简体   繁体   中英

JS filter textbox input

I hope this isn't a daft question. I expected google to be promising but I failed today.

I have a textbox <input type="text" id="input1" /> that I only want to accept the input /^\\d+(\\.\\d{1,2})?$/ . I want to bind something to the keydown event and ignore invalid keys but charCode isn't robust enough. Is there a good jQuery plugin that does this?

The affect I want to achieve is for some one to type 'hello world! 12.345' and want all characters to be ignored except '12.34' and the textbox to read '12.34'. Hope this is clear.

Thanks.

I don't think you need a plugin to do this; you could easily attach an event and write a simple callback to do it yourself like so:

$('#input1').keyup(function()
{
    // If this.value hits a match with your regex, replace the current 
    // value with a sanitized value
});

try this:

$('#input1').change(function(){
    if($(this).data('prevText') == undefined){
          $(this).data('prevText', ''); 
    }
    if(!isNaN($(this).val())){
        $(this).val($(this).data('prevText'))
    } 
    else {
        //now do your regex to check the number settings
        $(this).data('prevText', $(this).val()); 
    }

})

the isNAN function checks to make sure the value is a number

$('#input1').bind('keyup', function() {
    var val = $(this).val();
    if(!val)
        return;
    var match = val.match(/^\d+(\.\d{1,2})?$/);
    if(!match)
        return;
    //replace the value of the box, or do whatever you want to do with it
    $(this).val(match[0]);
});

jQuery Keyfilter

Usage:

$('#ggg').keyfilter(/[\dA-F]/);

It also supports some pre-made filters that you can assign as a css class.

$('input1').keyup(function(){
    var val = $(this).val().match(/\d+([.]\d{1,2})?/);
    val = val == null || val.length == 0 ? "" : val[0];
    $(this).val(val);
});

You should look at jQuery validation . You can define your own checking methods like this here .

I found the solution.

  1. Cache the last valid input on keydown event
  2. Rollback to last valid input on keyup event if invalid input detected

Thus:

var cache = {};
$(function() {
    $("input[regex]").bind("keydown", function() {
        var regex = new RegExp($(this).attr("regex"));
        if (regex.test($(this).val())) {
            cache[$(this).attr("id")] = $(this).val();
        }
    });
    $("input[regex]").bind("keyup", function() {
        var regex = new RegExp($(this).attr("regex"));
        if (!regex.test($(this).val())) {
            $(this).val(cache[$(this).attr("id")]);
        }
    });
});

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