Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add two functions to window.onload

I have two functions on my form except one does not work if the other is active. Here is my code:

window.onload = function(event) {     var $input2 = document.getElementById('dec');     var $input1 = document.getElementById('parenta');     $input1.addEventListener('keyup', function() {         $input2.value = $input1.value;     }); }  window.onload=function(){     document.getElementById('enable').onchange=function(){         var txt = document.getElementById('gov1');         if(this.checked) txt.disabled=false;         else txt.disabled = true;     }; }; 

What I mean is that when I have both these functions in my form the second function works fine but the first will not work, if take out the second function the first one will work like normal, why is this happening? Is it because of the names?

like image 815
AJJ Avatar asked May 22 '13 03:05

AJJ


People also ask

Can you have two window onload functions?

You can not bind several functions to window. onload and expect all of these functions will be executed.

Can you have multiple functions in one JavaScript file?

To import multiple functions from a module in JavaScript, specify an object with the function names you want to import. Notice how you do not need to use the . js extension in the file path. Also, remember you have to change the path from which to import if the module is located in another folder.

What is the difference between onload () and document ready ()?

The main differences between the two are: Body. Onload() event will be called only after the DOM and associated resources like images got loaded, but jQuery's document. ready() event will be called once the DOM is loaded i.e., it wont wait for the resources like images to get loaded.


1 Answers

window.addEventListener("load",function(event) {     var $input2 = document.getElementById('dec');     var $input1 = document.getElementById('parenta');     $input1.addEventListener('keyup', function() {         $input2.value = $input1.value;     }); },false);  window.addEventListener("load",function(){     document.getElementById('enable').onchange=function(){         var txt = document.getElementById('gov1');         if(this.checked) txt.disabled=false;         else txt.disabled = true;     }; },false); 

Documentation is here

Note that this solution may not work across browsers. I think you need to rely on a 3-rd library, like jquery $(document).ready

like image 68
Khanh TO Avatar answered Oct 08 '22 08:10

Khanh TO