How can I limit possible inputs in a HTML5 “number” element?

前端 未结 26 2546
感动是毒
感动是毒 2020-11-22 05:12

For element, maxlength is not working. How can I restrict the maxlength for that number element?

26条回答
  •  一生所求
    2020-11-22 05:24

    As I found out you cannot use any of onkeydown, onkeypress or onkeyup events for a complete solution including mobile browsers. By the way onkeypress is deprecated and not present anymore in chrome/opera for android (see: UI Events W3C Working Draft, 04 August 2016).

    I figured out a solution using the oninput event only. You may have to do additional number checking as required such as negative/positive sign or decimal and thousand separators and the like but as a start the following should suffice:

    function checkMaxLength(event) {
    	// Prepare to restore the previous value.
    	if (this.oldValue === undefined) {
    		this.oldValue = this.defaultValue;
    	}
    
    	if (this.value.length > this.maxLength) {
    		// Set back to the previous value.
    		this.value = oldVal;
    	}
    	else {
    		// Store the previous value.
    		this.oldValue = this.value;
    		
    		// Make additional checks for +/- or ./, etc.
    		// Also consider to combine 'maxlength'
    		// with 'min' and 'max' to prevent wrong submits.
    	}
    }

    I would also recommend to combine maxlength with min and max to prevent wrong submits as stated above several times.

提交回复
热议问题