javascript, getelementbyname and focus

Brian picture Brian · Oct 14, 2014 · Viewed 7.4k times · Source

I am trying to create function that will look at the username if it is not valid send an alert to the user, clear the username field, and put the username field back into focus. I am trying to do this all with the getElementsBynName() function. It is all working with the exception of getting the field back into focus. My code is below. Does anyone have any suggestions.

function uchecker(uname)
{
var validUname = uname.search(/^\[email protected]$/);
if(validUname != 0)
{
    alert("You have entered an invalid username. \n The username must be a valid @sju.edu    email    address value " + document.getElementsByName('uname')[0].value);
    document.getElementsByName('uname')[0].value = null;
    document.getElementsByName('uname')[0].focus();

    /I have also tried  document.getElementsByName('uname').focus, document.getElementsByName('uname')[0].value.focus();
}

}

So it appears that before the Java script runs the field that is in focus changes to the next field, my password input box...which also has its own validation function. I there a way to get my javascript code to run for my username field before the next textbox (password box) is takes focus?

Answer

Aravindh Gopi picture Aravindh Gopi · May 5, 2017

JavaScript:

document.getElementsByName('name')[0].focus()

Jquery:

$("#name")[0].focus()

function valid(){
  var nameObj = document.getElementsByName("testing");
  for(var i=0; i<nameObj.length; i++){
    if(nameObj[i].value == ""){
      //$(nameObj)[i].focus();  //Jquery
      nameObj[i].focus();       //Js
      alert("Please Fill all the text boxes");
      break;
    }
  }
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.input-sm{
  width:200px
}
</style>
<input name="testing" class="form-control input-sm" type="text" id="test_01"/><br> 

<input name="testing" class="form-control input-sm" type="text" id="test_02"/><br>
<input name="testing" class="form-control input-sm" type="text" id="test_03"/><br>
<input name="testing" class="form-control input-sm" type="text" id="test_04"/><br>
<input type="button" class="btn btn-primary" onclick ="valid()" value="Click Me"/>