Hi
I have below code . When alert is uncommented the focus is on first column otherwise no.
JavaScript
window.onload = function () {
/*alert("hi");*/
var empCodeField = document.getElementById("");
empCodeField.focus();
};
***********************
Code *Thanks

Naimish MakwanaRank #324 · 7.7K reputationPosted Sep 6, 2024, 7:29 AM EDT
It seems like the focus issue is related to the timing of when the
focus()method is called. When thealertis uncommented, it delays the execution of thefocus()method, allowing the DOM to fully load. Without thealert, thefocus()method might be called before the DOM is fully ready.To fix this, you can use the
setTimeoutfunction to delay the focus call slightly, ensuring the DOM is fully loaded:window.onload = function () { setTimeout(function() { var empCodeField = document.getElementById(""); empCodeField.focus(); }, 0); };This should ensure that the focus is set on the
txtEmployeeCodefield regardless of thealert.Thanks
Ramco RamcoRank #462 · 5.4K reputationPosted Sep 6, 2024, 7:38 AM EDT
Hi Naimish
Even now it is also not working. I am attaching full Aspx page
Users window.onload = function () { setTimeout(function () { /* alert("hi");*/ var empCodeField = document.getElementById(""); empCodeField.focus(); }, 0); }; Dashboard Employee Master Data Add Employee Back General Code * Name * Father Name Mother Name Gender Male Female Maritial Status UnMarried Married Date of Birth * Status Active Blocked Address Info Address1 Address2 City * State * Pincode * Phone-1 Phone-2 Back });Thanks
Naimish MakwanaRank #324 · 7.7K reputationPosted Sep 6, 2024, 7:49 AM EDT
Try this script
Sys.Application.add_load(function () { var empCodeField = document.getElementById(""); empCodeField.focus(); });Thanks
Ramco RamcoRank #462 · 5.4K reputationPosted Sep 6, 2024, 7:53 AM EDT
Hi Naimish
Written below code but not working still.
Thanks
Uday DodiyaRank #239 · 10.3K reputationPosted Sep 7, 2024, 5:42 AM EDT
Hi Ramco,
There is following possibility, please check
1.Check if empCodeField is Found: Add a console.log(empCodeField); before calling empCodeField.focus() to see if it's null or defined.
2. Use window.onload Correctly: Make sure that the window.onload function is executing only after all elements are loaded. You can also add a console log to check if the element is correctly found.
3. Place Script at the End of the Body: Moving your script to the end of the body ensures that all elements are rendered before your script executes.
4. Use document.addEventListener("DOMContentLoaded", function() {...});: This event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
Code :
Users Back document.addEventListener("DOMContentLoaded", function () { var empCodeField = document.getElementById(""); console.log(empCodeField); // Log to check if it's found if (empCodeField) { empCodeField.focus(); } });