-2

I have a script to select form options. How can I change the document ready function to Javascript instead of using jQuery?

$(document).ready(function () {
    function FormFill() {
            if {
                var el1 = document.getElementsByName("FormOption1")[0];
            if(typeof el1 !== 'undefined') {el1 = 1;}         
                var el2 = document.getElementsByName("FormOption2")[0];
            if(typeof el2 !== 'undefined') {el2 = 2;}  
            }, 100);
        }
    }
setTimeout(FormFill,5000);
});
Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Jay Dilla
  • 33
  • 1
  • 5
  • 1
    `DOMContentLoaded` is the JS equivalent to `$(document).ready`. Is that what you need? – Sebastian Simon Feb 11 '18 at 21:16
  • Check for extended answer: https://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery – qwermike Feb 11 '18 at 21:17
  • FYI `document.getElementsByName("FormOption1")[0]` is wasteful as it scans the entire DOM, when you are only interested in the first one found. Also, it returns a "live" node list. Use `document.querySelector("form[name='FormOption1']")` instead. – Scott Marcus Feb 11 '18 at 21:21

1 Answers1

0

Use DOMContentLoaded. Here is the full example.

document.addEventListener("DOMContentLoaded", function(event) {
    function FormFill() {
            if {
                var el1 = document.getElementsByName("FormOption1")[0];
            if(typeof el1 !== 'undefined') {el1 = 1;}         
                var el2 = document.getElementsByName("FormOption2")[0];
            if(typeof el2 !== 'undefined') {el2 = 2;}  
            }, 100);
        }
    }
    setTimeout(FormFill,5000);
});
Vitalii Chmovzh
  • 2,495
  • 4
  • 12
  • 24
  • Seems to be a few errors now. [1] just on the first variable 'Expected an identifier and instead saw var' [2] on the closing braces 'Expected an assignment or function call and instead saw an expression' – Jay Dilla Feb 11 '18 at 21:45