focus Javascript does not work for me

0

why focus () does not work ?? this is the code ...

var pcart =document.getElementById('pcart');
if ((parseInt(pcart.value)) != 100){
      pcart.focus();
      alert ("debe valer 100");
      return false;}
<input type="text" id="pcart" name="cartones"/>
    
asked by Pablo Chaco 19.04.2016 в 14:11
source

3 answers

0

I already found the solution! hehe

setTimeout (function () {pcart.focus ();}, 1);

It would stay like this:

var pcart =document.getElementById('pcart');
if ((parseInt(pcart.value)) != 100){
      alert ("debe valer 100");
      setTimeout(function(){pcart.focus();}, 1);    
      return false;}
<input type="text" id="pcart" name="cartones"/>
    
answered by 19.04.2016 / 14:47
source
1

The Event would be missing in which the If should be executed and then the focus. I did it with a button as an example.

function Focus(){
var pcart =document.getElementById('pcart');
if ((parseInt(pcart.value)) != 100){
      pcart.focus();
      alert ("debe valer 100");
      return false;}};
<input type="text" id="pcart" name="cartones"/>
<input type="button" id="pcart" value="Clik Para evento" onclick="Focus()" name="cartones"/>
    
answered by 19.04.2016 в 14:19
1

The correct thing (if it were a validation) would be to put it in the blur event:

window.addEventListener('load', function(){
    pcart.addEventListener('blur', function(){
         if(parseInt(this.value,10) != 100){
             alert("debe valer 100");
             this.focus();
         }
    });
});

This also has some problems, and is that if the user will not be able to leave the page without changing the value (or not naturally).

The ideal would be to put a text next to it and only focus the first time or if the value changed. You have to pay attention to the user experience.

    
answered by 21.04.2016 в 14:54