Deselect text using Javascript

I have two input tags with a numeric identifier in the form on the same html page. In focus, I would like to set the value of the second input of the first and second characters of the first input. Then I want to deselect the text in the second input. Is there a way to do this? I wrote this HTML code:

<label>Num. Fattura: <input type="text" name="numfattura1" onkeypress="return event.keyCode != 13" id="1" /> </label> <label>Importo: <input type="text" name="importo1" onkeypress="return event.keyCode != 13" /> </label> <br /> <label>Num. Fattura: <input type="text" name="numfattura2" onkeypress="return event.keyCode != 13" id="2" onfocus="twoDigits(2)" /> </label> <label>Importo: <input type="text" name="importo2" onkeypress="return event.keyCode != 13" /> </label> <br /> 

And this javascript function:

 function twoDigits(id){ var previousId = id - 1; var prevoiusValue = document.getElementById(previousId).value; document.getElementById(id).value = prevoiusValue.substring(0,2); document.selection.empty(); window.getSelection().removeAllRanges() } 

I cannot find how to deselect the text that will be selected automatically.

+4
source share
3 answers

set selectStart and selectionEnd with setTimeOut.

http://jsfiddle.net/enQvT/ works in firefox.

 function twoDigits(id){ var previousId = id - 1; var prevoiusValue = document.getElementById(previousId).value; var elem = document.getElementById(id); setTimeout(function() { elem.selectionStart=0; elem.selectionEnd=0; }, 0); elem.value = prevoiusValue.substring(0,2); } 
+1
source

You can also delete and replenish input. If you want to test:

 <input type="textfield" id="aaa" value="aaa" /> <input type="textfield" id="bbb" value="bbb" onmouseover="empty()" /> <script> var empty = function() { var ipt = document.getElementById('aaa'); var iptval = ipt.value; ipt.value = ""; ipt.value = iptval; } </script> 
+1
source

Call .focus() on another form element.

0
source

Source: https://habr.com/ru/post/1380437/


All Articles