1

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"

ksav
  • 20,015
  • 6
  • 46
  • 66
Peter
  • 101
  • 8
  • 1
    So if the value is `12` and someone types `3`, you want the value to become `23`, is that correct? Also, please add your current code to the question. – Rory McCrossan Dec 19 '18 at 11:40
  • No @RoryMcCrossan. If value is 12 and someone types 3, the value should be 3. Have edited and added code to fix the maximum input – Peter Dec 19 '18 at 11:45
  • In that case I don't see any issue as your description is how the elements already work. – Rory McCrossan Dec 19 '18 at 11:46
  • `` So the max allowed number is 2. If User enters, say 1, value is 1. If he enters 12, value will be 12. if he enter 1234, value will be 12. Now if user select the entered `12` and types in a new number, nothing happens. My requirement is in this case the new number (max 2 numbers) should be added to the input – Peter Dec 19 '18 at 11:48
  • Why not just use `maxlength`? It does what you need in a completely standard way which users are accustomed to, and won't break if someone has JS disabled. – Rory McCrossan Dec 19 '18 at 11:51

2 Answers2

2

You can use tel instead of number like:

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

So your edit box still accepts only number and input.selectionStart and input.selectionEnd are valid.

Please see this link: Failed to execute 'setSelectionRange' on 'HTMLInputElement': The input element's type ('number') does not support selection

Nick Mehrdad Babaki
  • 11,560
  • 15
  • 45
  • 70
0

selectionStart, selectionEnd are not allowed for type number. you have to change type to text or other valid type.

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

Also check this : selectionStart/selectionEnd on input type="number" no longer allowed in Chrome

lbhise
  • 136
  • 5