elem.select() works only in IE ?!?

Discussion in 'JavaScript' started by KatieK, Sep 20, 2007.

  1. #1
    I have a form with a bunch of paired text input fields named 'biggerx' and 'smallerx' where x increases with each row in a field. I've written a function, check_nums_orig() below, to compare the numbers in the pair of fields. If the 'smaller' number is larger than the 'bigger' one, an error will pop up and the wrong 'smaller' text field will be selected.

    function check_nums_orig(smaller, bigger)
    	{	if  ( (1*bigger.value) >= (1*smaller.value) )
    		{  document.getElementById(smaller.id).style.backgroundColor = "#FFFFFF"; }
    		else
    		{  alert("The number in the 'Smaller' box must be \nSMALLER than the number in the 'Bigger' box.  \nTry again.");
    		   smaller.style.backgroundColor = "#FFFFCC";
    		   smaller.select();
    		}
    	}
    Code (markup):
    Here is the form in the HTML:
    <form name="theform" action="">
    <fieldset>
    	<h3>Bigger <span style="padding-left: 7em;">Smaller</span></h3>
    	<input id="bigger1" type="text" />
    	<input id="smaller1" name="smaller1" onblur="check_nums_orig(this, document.getElementById('bigger1'));" type="text" /><br />
    	<input id="bigger2" type="text" />
    	<input id="smaller2" name="smaller2" onblur="check_nums_orig(this, document.getElementById('bigger2'));" type="text" /><br />
    	<input id="bigger3" type="text" />
    	<input id="smaller3" name="smaller3" onblur="check_nums_orig(this, document.getElementById('bigger3'));" type="text" /><br />
    </fieldset>
    </form>
    Code (markup):
    Alas, this script works only in IE. Firefox 2 and Opera will change the background color, but they will not select the input field.

    After quite a lot of head-banging, I had to use a slightly less elegant pair of functions, based in part off of Danny Goodman's excellent DHTML Cookbook. (Below.)

    function focusElement(formName, elemName) {
        var elem = document.forms[formName].elements[elemName];
        elem.focus();
        elem.select();
    }
    function check_nums(smaller, bigger)
    	{	if  ( (1*bigger.value) >= (1*smaller.value) )
    		{  document.getElementById(smaller.id).style.backgroundColor = "#FFFFFF"; }
    		else
    		{  alert("The number in the 'Smaller' box must be \nSMALLER than the number in the 'Bigger' box.  \nTry again.");
    		   smaller.style.backgroundColor = "#FFFFCC";
    		   setTimeout("focusElement('" + smaller.form.name + "', '" + smaller.name + "')", 0);
    		}
    	}
    Code (markup):
    My question is, why doesn't the check_nums_orig() function work? I tested removed setTimeout from the mix, and Goodman's script was still functional. I'd appreciate any light thrown on the subject.

    Thanks!

    (I've attached an HTML file so you can download the HTML and scripts to play with.)
     

    Attached Files:

    KatieK, Sep 20, 2007 IP