How can I execute this code in HTML on page load?
<script>
window.onload = $(function(){
$("#name1, #name2").val("").attr("disabled",true);
};
</script>
I have tried this code but it does not work.
9 Answers 9
Better to use the on() handler:
$(window).on('load', function(){
$("#name1, #name2").val("").attr("disabled",true);
});
or document.ready() if you aren't waiting for particular elements to load:
$(document).ready(function(){
$("#name1, #name2").val("").attr("disabled",true);
});
Comments
You just have an extra $( that you don't need, and a missing closing }...
window.onload = function() {
$("#name1, #name2").val("").attr("disabled",true);
};
Although that gets your code working, you could probably run this when the DOM is ready (which is quicker than waiting for all the images to load)...
$(function() {
$("#name1, #name2").val("").attr("disabled",true);
});
Comments
You can use this when you only want to access your DOM:
$(document).ready(function() { /* code */ });
$(function() { /* code */ }); // shorthand function (is identical)
If you require all other resources (styles, scripts, iframes, images, etc.) to be loaded too (eg. get an image dimensions), you need to use this:
$(window).on('load', function() { /* code */ });
Comments
You are mixing up JavaScript's way of doing things with jQuery's way of doing things.
Using windows.onload = ... is how you assign a function to be called after the load event occurs in JavaScript.
Using $(function(){...}) is jQuery syntax for $(document).ready(function(){}) which essentialy is the same thing, jQuery's document ready also triggers after load but unlike unlike windows.onload before images are loaded.
Use one or the other syntax.
Either use JavaScript like this:
window.onload = function(){
$("#name1, #name2").val("").attr("disabled",true);
}
Or one of jQuery's alternatives:
$(function(){
$("#name1, #name2").val("").attr("disabled",true);
})
$(document).ready(function(){
$("#name1, #name2").val("").attr("disabled",true);
})
$(window).ready(function(){
$("#name1, #name2").val("").attr("disabled",true);
})
Comments
You should close your function codeblock like this.
<script>
window.onload = $(function(){
$("#name1, #name2").val("").attr("disabled",true);
});
</script>
Comments
Use This, Remove window.OnLoad
$(function(){
$("#name1, #name2").val("").attr("disabled",true);
});
SEE DEMO
Comments
You could use this syntax:
$(function(){
$("#name1, #name2").val("").attr("disabled",true);
});
Comments
Try this :
window.onload = function () {
// do stuff here
$("#name1, #name2").val("").attr("disabled",true);
}
Comments
You forget to close " }); " :
<script>
window.onload = $(function(){
$("#name1, #name2").val("").attr("disabled",true);
});
</script>
onloadfunction