Reputation: 129
I have this following script:
$(function user_type(){
/* Change select box values */
$(document).on("change",".user_type",function(){
var user_type = $(this).data('user_type');
$.post(base_url+"index.php/manage/load_type",{user_type: user_type},function(data){
var data_obj = JSON.parse(data);
$('#yehida').empty().append('please choose');
switch (user_type) {
case 1:
$.each(data_obj, function (i, item) {
$('#yehida').append($('<option>', {
value: 0,
text : 'no records'
}));
});
break;
case 2:
$.each(data_obj, function (i, item) {
$('#yehida').append($('<option>', {
value: item['id'],
text : item['department_name']
}));
});
break;
}
This script works only onchange. I want it to run also when the page is loaded. What do i need to add\change?
Upvotes: 0
Views: 2012
Reputation: 337560
You need to extract out the logic of the handler to its own function. You can then call it on load and on select change. Try this:
function foo() {
var user_type = $(this).data('user_type');
$.post(base_url + "index.php/manage/load_type", {
user_type: user_type
}, function (data) {
var data_obj = JSON.parse(data);
$('#yehida').empty().append('please choose');
switch (user_type) {
case 1:
$.each(data_obj, function (i, item) {
$('#yehida').append($('<option>', {
value: 0,
text: 'no records'
}));
});
break;
case 2:
$.each(data_obj, function (i, item) {
$('#yehida').append($('<option>', {
value: item['id'],
text: item['department_name']
}));
});
break;
}
})
}
/* Change select box values */
$(document).on("change", ".user_type", foo)
/* on load */
$.proxy(foo, $('.user_type'))();
Note that $.proxy
is required on the load call to maintain the scope of this
within the function.
Upvotes: 2