In my jquery code, I am trying to //Do things every time the page is reloaded/refreshed and when the select box is clicked. But when I add the ready function (as in document is ready,) yet what is supposed to go inside //Do things, only gets executed with a click event, but not ready.
How can I fix this?
jQuery(document).ready(function(){
jQuery("select").bind("change ready", function(){
//Do things
});
In my jquery code, I am trying to //Do things every time the page is reloaded/refreshed and when the select box is clicked. But when I add the ready function (as in document is ready,) yet what is supposed to go inside //Do things, only gets executed with a click event, but not ready.
How can I fix this?
jQuery(document).ready(function(){
jQuery("select").bind("change ready", function(){
//Do things
});
Share
Improve this question
edited Mar 16, 2012 at 7:24
Anuj Balan
7,73123 gold badges61 silver badges94 bronze badges
asked Mar 15, 2012 at 3:18
Dean FellDean Fell
1
- this is stack overflow (outdated ment about needing to be moved to SO) – govinda Commented Jan 15, 2013 at 4:30
4 Answers
Reset to default 4You can simply pull out the code into another function, and call that both on page load and on change:
jQuery(document).ready(function(){
var func = function() {
// do things
};
// this does things whenever the <select> changes
jQuery("select").on("change", func);
// this does things once, when the page loads
func();
});
I also changed bind
to the remended on
instead (as of jQuery 1.7) -- this does not change the behavior at all.
I think you are looking for the .trigger method in jQuery, you want to trigger the function in your bind event:
jQuery(document).ready(function(){
jQuery("select").bind("change", function(){
//Do things
}).trigger("change");
});
The document.ready()
function waits until your whole document is loaded and the dom tree is built. Thats why it is a good idea to wrap your code within the document.ready()
. If you didn't do this, it might happen that your call jQuery("select")
does not find any element, because there is no domtree yet.
Now if you want to //Do things
when clicking upon your select
elements, you can either:
jQuery("select").click(function(){
});
or
jQuery("select").on("click", function(){
});
This binds a handler for a click-event to each of your select
elements.
Check out the jquery docs for more info.
you can do this:
$(function(){
$(":checkbox").click(function(){
// do your anything
});
});