Link to home
Start Free TrialLog in
Avatar of tonMachine100
tonMachine100

asked on

load function on page load

I'm customising a template in opencart. Im working on the product page which contains a number of options for a product. I've got one option (a select drop-down, which can have 3 possible answers - Yes, No or undefined), and two text box options. I want to link the select drop down option to the text box options so that:

when the customer selects Yes the two text boxes appear.
when the customer selects No the two text boxes hide
when the customer selects the default option (undefined), or when the page loads (and the value is undefined) the text boxes hide.

I think im nearly there. This script is run when the customer changes the value in the drop down.
The class of the select is called  class="target".
The value selected in the drop down is stored in a custom attribute called data-foo=""
The two text box questions are within the mySlideContent2 and mySlideContent divs.

 
<script type="text/javascript">
$(function(){
    $('.target').change(function(){
        var selected = $(this).find('option:selected');
       	$('#foo').html(selected.data('foo')); 

alert(selected.data('foo'));

	if (selected.data('foo') == "Yes") {
     		$(function(){
		
			$('#mySlideContent2').slideDown('slow');
			$('#mySlideContent').slideDown('slow');
					return false;	
		});
    	
     	}      
       	if (selected.data('foo') == "No") {
    	
    		$(function(){
		
			$('#mySlideContent2').slideUp('slow');
			$('#mySlideContent').slideUp('slow');
					return false;
		});
    	
       	}   
    	if (selected.data('foo') === undefined) {
       		$(function(){
		
			$('#mySlideContent2').slideUp('slow');
			$('#mySlideContent').slideUp('slow');
					return false;
		});
       	} 
    }).change();
});
</script>

Open in new window


This works fine but i also need this function to run when the page loads - this is where im struggling.

I've added this code below to call the function when the page loads. It appears to be running on page load (i can validate this beacuse the alert(selected.data('foo')); message box appears displaying the value stored in data-foo ,  but the text boxes are not hiding if the value is undefined or No.

<script>
$(document).ready(function() {
  $('.target').change();
});
</script>

Open in new window


Any ideas why this might be. Are the elements in the form being generated after the function is being run?

Many thanks
SOLUTION
Avatar of Marco Gasi
Marco Gasi
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial