Find if text is selected for input type number

时间:2018-12-19 11:37:43

标签: javascript jquery

I have an <input type="number" which can store maximum two digits. This is achieved by using event.preventDefault();.

function allowMaxNumbers(element, event, maxLength){
if(element.value.length==maxLength&& event.keyCode!=8 && event.keyCode!=46 && event.keyCode!=9){
    if (event.preventDefault){
        event.preventDefault();
    }    
    return false;
}

}

If user selects the input and types in another number, the new number should be inputted replacing the old input. Is there a way in javascript/jQuery to find if some text is selected in the input?

I followed the question How to know if the text in a textbox is selected? and tried input.selectionStart and input.selectionEnd but that is not working for input type="number"

2 个答案:

答案 0 :(得分:1)

您可以使用tel代替数字,例如:

<input type="tel" name="anything" />

因此您的编辑框仍然只接受数字和输入。selectionStart和input.selectionEnd有效。

请查看此链接:Failed to execute 'setSelectionRange' on 'HTMLInputElement': The input element's type ('number') does not support selection

答案 1 :(得分:0)

类型编号不允许使用

selectionStart,selectionEnd。您必须将类型更改为文本或其他有效类型。

签出:http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#do-not-apply

也请检查以下内容: selectionStart/selectionEnd on input type="number" no longer allowed in Chrome