Jquery Focus in the field

Asked

Viewed 7,834 times

1

Is there any method in jQuery that I can focus on input with error? I am trying to validate without using the validation libs from Jquery. My problem is this: the user is at the bottom of the screen and my validation field is in the middle. I wanted to redirect the user to the field that is displaying validation message.

inserir a descrição da imagem aqui

Code of the jQuery :

   $(document).ready(function()
    { 
        $('#region_btnSave').click(function ()
        {  
            var txtHValue = $("#region_tabVersao_N_txtH").val();
            var txtMValue = $("#region_tabVersao_N_txtM").val();

            if (txtMValue == '' && txtHValue == '') {
                $("#errortxtM").text("Obrigatório").focus();
                $("#errortxtH").text("Obrigatório");
                $("#region_tabVersao_N_txtM").keydown(function () {
                    $("#errortxtM").text("").focus()
                });
                $("#region_tabVersao_N_txtH").keydown(function () {
                    $("#errortxtH").text("")
                }); 
                return false;
            } else if (txtMValue == '') {
                $("#errortxtM").text("Obrigatório");
                $("#region_tabVersao_N_txtM").keydown(function () {
                    $("#errortxtM").text("")
                });
                return false;

            } else if (txtHValue == '') {
                $("#errortxtH").text("Obrigatório");
                $("#region_tabVersao_N_txtH").keydown(function () {
                    $("#errortxtH").text("")
                });
                return false;
            }
            else {
                //not all text fields are valid
                $("#region_tabVersao_N_txtH").after('', null);
                $("#region_tabVersao_N_txtM").after('', null);
            }

    });
    });

And the HTML:

      <span class="error" id="errortxtM" style="color:#FF0000; font-size:10px"></span>

He is doing the validation certificate however if the user has at the end of the screen ,he will not be able to see the message "Required".

  • 1

    Shouldn’t be $("#errortxtM").focus(); instead of $("#errortxtM").text("Obrigatório").focus();???

  • https://stackoverflow.com/questions/14719269/assign-scroll-animation-to-focus-in-jquery .

  • errortxtM seems to be the id of the text below the input, what is the id of input? Why is it that you have to give the focus.

2 answers

2

You must apply the .focus in the input. It won’t work if you add in another element like span, div etc..

Thus:

$("#region_tabVersao_N_txtM").focus().keydown(function() {
    $("#errortxtM").text("")
});

Or even with JS Puro

document.querySelector("#region_tabVersao_N_txtM").focus().keydown(function() {
    $("#errortxtM").text("")
});

Example with jQuery:

$('#region_btnSave').click(function() {
  var txtHValue = $("#region_tabVersao_N_txtH").val();
  var txtMValue = $("#region_tabVersao_N_txtM").val();

  if (txtMValue == '' && txtHValue == '') {
    $("#errortxtM").text("Obrigatório");
    $("#errortxtH").text("Obrigatório");
    $("#region_tabVersao_N_txtM").focus().keydown(function() {
      $("#errortxtH").text("")
    });

    $("#region_tabVersao_N_txtH").focus().keydown(function() {
      $("#errortxtM").text("")
    });
    return false;
  }
});
div {
  height: 50px;
}

span {
  color: Red;
  display: block;
  width: 100%
}

.big {
  height: 500px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <label for="region_tabVersao_N_txtH">Input 1</label>
  <input id="region_tabVersao_N_txtH" />
  <span id="errortxtM"></span>
</div>

<div>
  <label for="region_tabVersao_N_txtM">Input 2</label>
  <input id="region_tabVersao_N_txtM" />
  <span id="errortxtH"></span>
</div>

<div class="big">Desça a página</div>

<div>
  <button type="butotn" id="region_btnSave">Save</button>
</div>

Js Puro

document.querySelector('#region_btnSave').addEventListener("click", () => {  
  var txtHValue = document.querySelector("#region_tabVersao_N_txtH").value;
  var txtMValue = document.querySelector("#region_tabVersao_N_txtM").value;

  if (txtMValue == '' && txtHValue == '') {
    document.querySelector("#errortxtM").innerText = "Obrigatório";
    document.querySelector("#errortxtH").innerText = "Obrigatório";
    
    document.querySelector("#region_tabVersao_N_txtH").focus();
    
    document.querySelector("#region_tabVersao_N_txtH").addEventListener("keydown", () => {
      document.querySelector("#errortxtM").innerText = "";
    });
    
     document.querySelector("#region_tabVersao_N_txtM").addEventListener("keydown", () => {
      document.querySelector("#errortxtH").innerText = "";
    });
    
    return false;
  }
});
div {
  height: 50px;
}

span {
  color:Red;
  display:block;
  width:100%
}

.big {
  height: 500px
}
<div>
  <label for="region_tabVersao_N_txtH">Input 1</label>
  <input id="region_tabVersao_N_txtH" />
  <span id="errortxtM"></span>
</div>

<div>
  <label for="region_tabVersao_N_txtM">Input 2</label>
  <input id="region_tabVersao_N_txtM" />
  <span id="errortxtH"></span>
</div>

<div class="big">Desça a página</div>

<div>
  <button type="butotn" id="region_btnSave">Save</button>
</div>

No need to add scrollTop, except if you want an animation. Example below.

$('#region_btnSave').click(function() {
  var txtHValue = $("#region_tabVersao_N_txtH").val();
  var txtMValue = $("#region_tabVersao_N_txtM").val();

  if (txtMValue == '' && txtHValue == '') {
    $("#errortxtM").text("Obrigatório");
    $("#errortxtH").text("Obrigatório");
    
    $("#region_tabVersao_N_txtM").keydown(function() {
      $("#errortxtH").text("")
    });

    $("#region_tabVersao_N_txtH").keydown(function() {
      $("#errortxtM").text("")
    });
    
    $("html,body").stop().animate({
      scrollTop:0
    }, 1000, function() {
      $("#region_tabVersao_N_txtH").focus()
    });
    
    return false;
  }
});
div {
  height: 50px;
}

span {
  color: Red;
  display: block;
  width: 100%
}

.big {
  height: 500px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <label for="region_tabVersao_N_txtH">Input 1</label>
  <input id="region_tabVersao_N_txtH" />
  <span id="errortxtM"></span>
</div>

<div>
  <label for="region_tabVersao_N_txtM">Input 2</label>
  <input id="region_tabVersao_N_txtM" />
  <span id="errortxtH"></span>
</div>

<div class="big">Desça a página</div>

<div>
  <button type="butotn" id="region_btnSave">Save</button>
</div>

1


You are applying .focus() an element that does not accept the method (span).

By focusing on the input, the screen will automatically scroll to it.

As your code has a lot of redundancy, I took the liberty and gave an optimized.

$(document).ready(function()
    { 

       $("#region_tabVersao_N_txtM, #region_tabVersao_N_txtH").keydown(function () {
           $(".error").text("");
       });

        $('#region_btnSave').click(function ()
        {  
            var txtHValue = $("#region_tabVersao_N_txtH");
            var txtMValue = $("#region_tabVersao_N_txtM");

            if (!txtMValue.val() && !txtHValue.val()) {
                txtHValue.focus();
                $("#errortxtH").text("Obrigatório");
            } else if (!txtMValue.val()) {
               txtMValue.focus();
                $("#errortxtM").text("Obrigatório");
            } else if (!txtHValue.val()) {
               txtHValue.focus();
                $("#errortxtH").text("Obrigatório");
            }
            else {
                //not all text fields are valid
                $("#region_tabVersao_N_txtH").after('', null);
                $("#region_tabVersao_N_txtM").after('', null);
                alert("ok");
            }
    });
 });
div{
    display: inline-block;
    border: 1px solid #000;
    margin: 3px;
    padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
   <input type="text" id="region_tabVersao_N_txtH" />
   <span class="error" id="errortxtH" style="color:#FF0000; font-size:10px"></span>
</div>
<div>
   <input type="text" id="region_tabVersao_N_txtM" />
   <span class="error" id="errortxtM" style="color:#FF0000; font-size:10px"></span>
</div>
<br />
Role para baixo e clique no botão
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<input value="Validar" type="button" id="region_btnSave" />

  • It worked, it’s like $("#errortxtH"). text("Required"); put an image together?

  • @Robsonoliveira has yes. There instead of using text, use html: $("#errortxtH").html("<img src='url_da_imagem' />Obrigatório");

  • Hi @Robsonoliveira, I saw that you marked my reply and then canceled. Found the other answer better or was by mistake?

  • Sorry ,I think I pressed more than once

Browser other questions tagged

You are not signed in. Login or sign up in order to post.