plus sign in html input type=number

后端 未结 3 1804
终归单人心
终归单人心 2020-12-12 03:56

Does anyone know if it\'s possible to add a plus sign in a html input type=number field? I have a scenario whereby users need to enter a modifier value which is either +1 t

相关标签:
3条回答
  • 2020-12-12 04:19

    I don't think it is possible to manipulate the input. the default is a "-" for negative and no sign for positive numbers.

    even if you checked a create UI frameworks like:

    Jquery UI, Bootstrap, Angular Material ...

    I guess the only solution is to write your own custom code.

    two scenarios are available:

    1- an input with Text and the manipulating will be in javascript.

    2- create a pipe in angular2 and give it to the element. which I think it is much easier than the first one.

    0 讨论(0)
  • 2020-12-12 04:19

    I hope this will help on you guys!!

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
      $(document).on('keypress','#input',function (e) {
        var keyCode = e.which;
    
        if ($(this).val().trim().charAt(0) == "\u002B") {
           if (  keyCode == 43 ) { 
              return false;
           }
        }
        else{
           for (var i = 1; i < $(this).val().length+1; i++) {
              if(i!=0){
                 if (  keyCode == 43 ) { 
                    return false;
                 }
              }
           }
         }
      });
    
      $(document).on('input', '#input', function() {
         this.value = this.value.replace(/[^+{1}|^0-9]/g,'');
      });
    </script>

    0 讨论(0)
  • 2020-12-12 04:25

    No it's not possible. The number field only accepts -, 0-9 and e to be entered. As a workaround you could place the + in the HTML before the input, eg:

    + <input type="number" />

    Alternatively you could use a standard type="text" input, but that would mean creating your own validation logic which would make the code much more complex.

    0 讨论(0)
提交回复
热议问题