In my web page, I created a new row in my data table at runtime. The new row consisted of two text boxes and I needed to set focus on first text box in the row.
I got the id of the text box element by inspecting the HTML code and tried to do the following:
In java code:
inputId =
executeJavaScript("selectDPTypeRow('"+inputId+"')" );
('executeJavaScript' is a custom method to execute JS code from Java code)
In JS code:
function selectNewRow(textBoxElementId){
var textBox = document.getElementById(textBoxElementId);
textBox.setFocus();
}
But this never worked as 'textBox' always gave null. I was baffled as to why should the element be not found in the page DOM since inputId was always correct. Later I realized that by the time the above code is called, the new elements have not yet been rendered on the page and hence the elements are not found.
To overcome this I introduced a timelag of half a second before the above code is called.
inputId =
executeJavaScript("setTimeout(\"selectDPTypeRow('"+inputId+"')\",500);");
This delay of 500 ms (or .5 seconds) ensured that elements were rendered by the time they were accessed!
Elementary, wasn't it :)
Comments