So I have an ajax script for cascading drop down forms.
At the moment it's called when the "master" drop down is changed or focused, using the jquery on() function. When the user selects an item from the master dropdown, the ajax script is called to load a php script that checks the sql DB for all the "children" of that master, which then populates the child drop down list.
$("select#master").on("change focus", function(){
var master = $("select#master option:selected").attr('value');
if (master.length > 0 ){
$.post("inc/fetchChild.php",
{
id: master
},
function(data){
$("#child").html( data );
});
};
});
This works all well and good - no dramas.
The problem is I want this script to fire on page load. This is because the form data at the next page is saved as session variables, so the user can go back and forth between the form stages and each form element checks to see if there is a associated session variable, and if there is, loads it up.
Im doing this because the form is very long and broken into 5 sections - so I dont want the customer losing their form data if they go back and forth.
So, I need this above script to fire on page load because if the user has already selected the child and master previous - then php loads the "master" drop down with the user selection already loaded and selected. This once the page has finished loading, the ajax script needs to fire - sees that the master is already loaded, and subsequently loads the children for that master.
So going back to the main problem. If I insert "ready" into the ".on("change focus", function()" function ..... .on("change focus ready", ... it doesn't work.
However If I copy and past the above functions contents into the root $(document).ready(function(){ function, it works fine! Like this:
$(document).ready(function(){
var master = $("select#master option:selected").attr('value');
if (master.length > 0 ){
$.post("inc/fetchChild.php",
{
id: master
},
function(data){
$("#child").html( data );
});
};
$("select#master").on("change focus", function(){
var master = $("select#master option:selected").attr('value');
if (master.length > 0 ){
..........................etc...
Problem is now I have pretty much a duplicate function, which isn't very efficient and a but ugly.
I hope I'm explaining myself clear enough...
Can I reconfigure this on function to fire on page load as well as when the user clicks on the master list?