I'm sorry if this question has already been asked, but i didn't find a solution.
I have 3 radios elements and I want to check the value when the selection changes and when the page loads.
I would do that by using only the on() function.
My problem is that only the change event is triggered.
Here is my current code :
$('.user').on('load change', function(){
if($(this).val() == 'client'){
$('#user_parent').removeAttr('disabled').closest('tr').show(200);
}else{
$('#user_parent').attr('disabled', 'disabled').closest('tr').hide(200);
}
});"
I also tried to replace load by ready, but it failed too. What the problem ? Isn't the load event available for a single element ?
The code is placed in $(document).ready(...), and the elements are all displayed when the page is sent.
Thanks
the load event will be called the moment all child elements of the listened element are loaded. in your case this might be before the ready event is called, thus rendering your handler to load (which is appended after document.ready) useless.
for reference see JQuery api where you will find the following:
The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.
this also means you need an URL, so you can listen to the load event. as you have not provided further code I assume you do indeed have an URL you can listen to.
This might be the most probable cause though. if you do not have any URL associated with (at least one) child element(s) there will be no load event you can listen to.
try this instead:
$(document).ready(function(){
checkUserVal();
$('.user').on('change', checkUserVal);
});
var checkUserVal = function(){
//do the check
if($('.user').val() == 'client'){
$('#user_parent').removeAttr('disabled').closest('tr').show(200);
}else{
$('#user_parent').attr('disabled', 'disabled').closest('tr').hide(200);
}
};
i made the code a method for improved readability ;)
As Vogel612 explained, load doesn't fire for most elements.
ready is only for document.
You can use each to run your event handler initially.
$(document).ready(function(){
$('.user')
.each(user_handler)
.on('change', user_handler);
});
var user_handler = function(){
// this
};
来源:https://stackoverflow.com/questions/17400152/jquery-on-load-event-on-a-single-element