What I am trying to do is verify that a textbox is all numeric, and if it isn't, clear it and set the focus back on the text box. I have gotten it to clear it, but it won't set the focus. <tr> <td><input type="text" name="billable_rate" id="billable_rate" onchange="calcTotal(this.value, billable_rate);"></td> </tr> <tr> <td><input type="text" name="travel_rate" id="travel_rate" onchange="calcTotal(this.value, travel_rate);"></td> </tr> HTML: function calcTotal(sText, field){ var ValidChars = "0123456789."; var IsNumber=true; var Char; var total = 0.00; var field2 = field.name; for (i = 0; i < sText.length && IsNumber == true; i++){ Char = sText.charAt(i); if (ValidChars.indexOf(Char) == -1){ IsNumber = false; } } if(true == IsNumber){ var billableRate = document.getElementById("billable_rate").value*1; var travelRate = document.getElementById("travel_rate").value*1; total = billableRate+travelRate; subTotal = document.getElementById('subTotal'); replaceText(subTotal, total); }else{ alert("not a valid number"); switch (field2){ case 'billable_rate': document.stuff.billable_rate.value = ''; var txtBox=document.getElementById("billable_rate"); if (txtBox==null)txtBox.focus(); break; case 'travel_rate': document.stuff.travel_rate.focus(); document.stuff.travel_rate.value = ''; break; } } } Code (markup): Any ideas are greatly appreciated. TIA
try switching the order of commands - first set the value to an empty string and only after set the focus.
I have it doing that under case: billable_rate, and the opposite way under case: 'travel_rate', but neither one work... I don't know why I always have so much trouble with setting the focus.
dodgy. anyway - look at this, working with a small hack via a 300ms timeout: http://www.jsfiddle.net/dimitar/kaCEG/2/ (function() { var slowFocus = function(what) { var timer; clearTimeout(timer); timer = setTimeout(function() { what.focus(); }, 300); }; var calcTotal = function(field) { var ValidChars = "0123456789."; var sText = field.value; var IsNumber=true; var Char; var total = 0.00; var field2 = field.name; for (i = 0; i < sText.length && IsNumber == true; i++){ Char = sText.charAt(i); if (ValidChars.indexOf(Char) == -1){ IsNumber = false; } } if(IsNumber){ var billableRate = document.getElementById("billable_rate").value*1; var travelRate = document.getElementById("travel_rate").value*1; total = billableRate+travelRate; subTotal = document.getElementById('subTotal'); replaceText(subTotal, total); } else { //alert("not a valid number"); switch (field2){ case 'billable_rate': field.value = ''; slowFocus(field); break; case 'travel_rate': field.value = ""; slowFocus(field); break; } } } document.getElementById("billable_rate").onchange = function() { calcTotal(this); }; document.getElementById("travel_rate").onchange = function() { calcTotal(this); }; })(); Code (javascript):