Quick Javascript Question

Discussion in 'JavaScript' started by ip076, Sep 17, 2005.

  1. #1
    I'm using this function to validate if an acceptable time, in 24 Hour Format, has been entered. I'm pretty new to Javascript, but I think I've got it pretty much figured out. Everything works well, the alert window is displayed, and the backround color is changed, but the element does not get focus, can one of you experts help out a newbie? Thanks!

    
    function validate_time(numtime) {
    	var strtime = numtime.toString();
    	var element = event.srcElement;
    	var wrng_clr = "yellow";
    	if(IsNumeric(strtime) == false) {
    		alert("You did not enter an acceptable time!");
    		element.style.backgroundColor = wrng_clr;
    		element.focus();
    	}
    
    	else if(strtime.charAt(2) < 0 || strtime.charAt(2) > 5) {
    		alert("You did not enter an acceptable time!");
    		element.style.backgroundColor = wrng_clr;
    		element.focus();
    	}
    
    	else if(numtime < 0 || numtime > 2400) {
    		alert("You did not enter an acceptable time!");
    		element.focus();
    		element.style.backgroundColor = wrng_clr;
    		
    	}
    	else {
    		element.style.backgroundColor = "white";
    	}
    }
    
    Code (markup):
     
    ip076, Sep 17, 2005 IP
  2. durango

    durango Guest

    Messages:
    83
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #2
    First question is when are you firing validate_time? It looks like you're trying to fire it during an event, such as an onblur?

    If this is the case and you have something like this:
    <input type="text" name="hour" onblur="validate_time(this.text);">
    Code (markup):
    I would change the parameter:
    <input type="text" name="hour" onblur="validate_time(this);">
    Code (markup):
    Then in your validate_time function do this:
    
    function validate_time(textbox) {
        var strtime = textbox.value;
        var elem = textbox;
        .....
        .....
                 elem.focus();
        .....
        .....
    }
    
    Code (markup):
    Hope this helps a bit..
     
    durango, Oct 17, 2005 IP