Question

i'm trying to make script which will replace all unwanted characters (from regexp) in input on keyup event. I tried everything but nothing works for me...

My code:

$('#form_accomodation_cell').on('keyup', 'input[name="accomodation_cell[]"]', function() {

    var value = $(this).val();
    var regex_cell = /^[0-9 \+]+$/g;

    if (!isNumeric(value, regex_cell))
    {
        var new_value = value.replace(regex_cell, '');
        alert(new_value);
    }

    function isNumeric(elem, regex_cell) {
        if(elem.match(regex_cell)){
            return true;
        }else{
            return false;
        }
    }

});
Was it helpful?

Solution

Try this:

$('#form_accomodation_cell').on("keyup", function () {
    var value = $(this).val();
    var regex_cell = /[^[0-9 +]]*/gi;
    var new_value = value.replace(regex_cell, '');
    alert(new_value);
});

See it here in action.

OTHER TIPS

I think you should try to catch the event and finaly write this way !

function validateNumber(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /^[0-9 \+]+$/g;
    if( !regex.test(key) ) {
   theEvent.returnValue = false;
   if(theEvent.preventDefault) theEvent.preventDefault();
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top