简体   繁体   中英

Jquery preventDefault not working on android 4.4 default browser

I am working with a angular and jquery based website. I have a text input field for validating array of floating numbers. My requirement is to restrict the user from entering alphabets, etc.

The problem is I am using e.preventDefault() but its not working in android default browser but working perfectly in android chrome.

I have searched a lot but unable to get any solution.

My sample code :-

 $('#test').keydown(function (e) {
      e.stopPropagation();
      e.preventDefault();
      e.returnValue = false;
      e.cancelBubble = true;
      return false;
});

I have also tried :-

$('#test').keydown(function (e) {
  if (e.preventDefault) {
       e.preventDefault();
    } else {
       e.returnValue = false;
  }
});

Working fiddle

Note:- I cannot use keypress event as the android default browser cannot listen this event.

I also had this problem with default browser on Android. preventDefault didn't help me, so I used .on jQuery function.

    $('#test').on('input',function () {
        var inputText = $(this).val();

        var resultText = inputText.replace(/[^0-9]/g, '');
        $(this).val(resultText);
    });

You can add to regex the other characters you need to be allowed. Hope it helps.

I don't know why you want to prevent a key event, but I think you just want to prevent entering of invalid chars. Let's see how you could resolve your problem without preventDefault :

(function(){ // anon function for scope

    var prevVal = $("#test").val(); // get initial value of input

    $('#test').on("input", function (e) { // input will also handle paste event. it handle every input'
        if(/*your `if` here*/ Math.random() > 0.3){
            this.value = prevVal; // You shall not pass!
        }
        prevVal = this.value; // save current valid value
    }); 

})();

http://jsfiddle.net/rk5wuubo/

I hope, it will solve your problem everywhere and never forget about "paste"!

If you are developing website based on angular you should solve the problem in angular way.

Here the sample how to do this.

The idea is to use NgModelController and FormController .

Please use $formatters of angularjs. This will help you check the viewValue before it is set to modelValue .

Please go through this document: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

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