Javascript Focus using .focus()

wewe

I have issue about the focus on javascript if if time_start > 24 the java script alert showed then focus or autofocs it on that textbox. but the focus is not working i don`t know why this is minor problem but please check this.

javascript

 function start_time(){

   var time_start = document.getElementById("start_t").value;
    if(time_start > 24){
        alert("Invalid Start time hours");
         document.getElementById('start_t').focus();
  } 
 }

html

 <input type="text" size="2" value="00" name="start" id="start_t" style="text-align: center;" onchange="start_time()">:

I want to do is in the value is invalid automatically focus on that textbox

vdua

I know a solution that works but don't have a valid reason for its working. There are two problems with your code

  1. comparing String with Integer

    function start_time(){
        var time_start = document.getElementById("start_t").value; 
        // time_start is a string. convert it into Integer first
        if(time_start > 24){ // you are comparing integer with string
            alert("Invalid Start time hours");
            document.getElementById('start_t').focus();
      } 
    }
    

    you need to change this function as below

    function start_time(){
         var time_start = parseInt(document.getElementById("start_t").value;
         if(isNaN(time_start) || time_start > 24){ 
             alert("Invalid Start time hours");
             document.getElementById('start_t').focus();
         }             
    }
    
  2. Doing focus on change event. For input type='text' change event is fired on blur. I have faced the problems whenever I put the field on focus using JavaScript on the 'change' event. see the fiddle. To overcome the problem there are two solutions,

    a. either do the stuff you are doing on click of a button, see the fiddle

    b. or do the focus with a timeout, fiddle

    setTimeout( function() { document.getElementById('start_t').focus()} ,1);
    

PS: Please mind my use of jQuery in the fiddles, I am a little lazy in using the native JavaScript functions

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related