jquery only allow input float number

前端 未结 13 1731
既然无缘
既然无缘 2020-12-01 06:28

i\'m making some input mask that allows only float number. But current problem is I can\'t check if multiple dots entered. Can you check those dots and prevent it for me?

13条回答
  •  天涯浪人
    2020-12-01 07:19

    Your code seems quite fine but overcomplicated.

    First, it is $(this).val().indexOf, because you want to do something with the value.

    Second, the event.which == 46 check is inside an if clause that's only passed when event.which != 46, which can never be true.

    I ended up with this which works: http://jsfiddle.net/VRa6n/3/.

    $('.number').keypress(function(event) {
        if(event.which < 46
        || event.which > 59) {
            event.preventDefault();
        } // prevent if not number/dot
    
        if(event.which == 46
        && $(this).val().indexOf('.') != -1) {
            event.preventDefault();
        } // prevent if already dot
    });
    

提交回复
热议问题