How to get the raw value an <input type=“number”> field?

前端 未结 4 1610
眼角桃花
眼角桃花 2020-11-22 11:57

How can i get the \"real\" value of an field?


I have an input box, and i\'m using newer HTML5

4条回答
  •  情深已故
    2020-11-22 12:40

    It doesn't answer the question, but the useful workaround is to check

    edQuantity.validity.valid
    

    The ValidityState of an object gives clues about what the user entered. Consider a type="number" input with a min and max set

    
    

    We always want to use .validity.valid.

    Other properties only give bonus information:

    User's Input  .value  .valid | .badInput  .rangeUnderflow  .rangeOverflow
    ============  ======  ====== | =========  ===============  ==============
    ""            ""      true   | false      false            false  ;valid because field not marked required
    "1"           "1"     true   | false      false            false  
    "10"          "10"    true   | false      false            false
    "0"           "0"     false  | false      true             false  ;invalid because below min
    "11"          "11"    false  | false      false            true   ;invalid because above max
    "q"           ""      false  | true       false            false  ;invalid because not number
    "³"           ""      false  | true       false            false  ;superscript digit 3
    "٣"           ""      false  | true       false            false  ;arabic digit 3
    "₃"           ""      false  | true       false            false  ;subscript digit 3
    

    You'll have to ensure that the the browser supports HTML5 validation before using it:

    function ValidateElementAsNumber(element)
    {
       //Public Domain: no attribution required.
       if ((element.validity) && (!element.validity.valid))
       {
          //if html5 validation says it's bad: it's bad
          return false;
       }
    
       //Fallback to browsers that don't yet support html5 input validation
       //Or we maybe want to perform additional validations
       var value = StrToInt(element.value);
       if (value != null)
          return true;
       else
          return false;
    }
    

    Bonus

    Spudly has a useful answer that he deleted:

    Just use the CSS :invalid selector for this.

    input[type=number]:invalid {
        background-color: #FFCCCC;
    }
    

    This will trigger your element to turn red whenever a non-numeric valid is entered.

    Browser support for is about the same as :invalid, so no problem there.

    Read more about :invalid here.

提交回复
热议问题