How can I limit possible inputs in a HTML5 “number

2018-12-31 09:11发布

For <input type="number"> element, maxlength is not working. How can I restrict the maxlength for that number element?

22条回答
无色无味的生活
2楼-- · 2018-12-31 09:40

Max length will not work with <input type="number" the best way i know is to use oninput event to limit the maxlength. Please see the below code for simple implementation.

<input name="somename"
    oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
    type = "number"
    maxlength = "6"
 />
查看更多
时光乱了年华
3楼-- · 2018-12-31 09:40

simple way to set maxlength for number inputs is:

<input type="number" onkeypress="if(this.value.length>=4) { return false;}" oninput="if(this.value.length>=4) { this.value = this.value.slice(0,4); }" />
查看更多
高级女魔头
4楼-- · 2018-12-31 09:41

HTML Input

 <input class="minutesInput" type="number" min="10" max="120" value="" />

jQuery

 $(".minutesInput").on('keyup keypress blur change', function(e) {

    if($(this).val() > 120){
      $(this).val('120');
      return false;
    }

  });
查看更多
孤独寂梦人
5楼-- · 2018-12-31 09:41

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.

查看更多
登录 后发表回答