jcadima
9/28/2016 - 8:27 PM

Hide div based on Dropdown selection and array condition

Hide div based on Dropdown selection and array condition

Other examples:
http://jsfiddle.net/Y3pW9/
http://jsfiddle.net/timur/ZmdcC/1/




<div class="form-group"> 
	<label>Vehicle</label>
	<select name="vehicle_type" id="vehicle_type" class="form-control" required>
		
		<?php

		 // List of Cars - REPEATER
		$cars = array() ;
		if( have_rows('vehicles_list_repeater') ): 
			while( have_rows('vehicles_list_repeater') ): the_row(); 
				$cars[] = get_sub_field('vehicle_type');
			endwhile; 
		endif; 

		foreach ( $cars as $car )  :  ?>	
			<option value="<?php echo $car; ?>" <?php setSelected( "vehicle_type", $car ) ?>><?php echo $car; ?></option>
		<?php  endforeach;  ?>				
	</select>
</div>


<!--  this will show depending on JS  -->
<div class="form-group chauffeur_options">     
   <label>Chauffeur</label>
	<label class="radio-inline"><input type="radio" name="optradio" id="optradio" value="Yes" <?php setChecked( "optradio", "Yes" )?>>Yes</label>
	<label class="radio-inline"><input type="radio" name="optradio" id="optradio" value="No" <?php setChecked( "optradio", "No" )?>>No</label>   
 </div>   





<script>
jQuery(function() {

	document.getElementById("vehicle_type").onchange = function() { 
		switchme(this); // pass 'this' current element to the switchme function
	}      

});	


  
function switchme(SNewSel) { 
	var chauffeur_cars =  ["Lamborghini", "Rolls", "Mercedes-Benz" , "Mercedes", "Rolls Royce" ]   ;
	var car_name = SNewSel.options[SNewSel.selectedIndex].text; // get car name from select dropdown
	//var car_name = car_index.replace("-", " ") ;
	var car_first = car_name.split(" ") ;  // get first letter of car name
	console.log(car_first[0]) ;
	console.log(car_name) ;

	// if selected car is found in the chauffeur cars show chauffeur options, else hide it
    if (jQuery.inArray(car_first[0], chauffeur_cars )!='-1') {
	    jQuery('.chauffeur_options').show() ;
       // alert(car_first[0] + ' is in the array!');
    } else {
        // alert(car_first[0] + ' is NOT in the array');
         jQuery('.chauffeur_options').hide() ;
    }	
	
	
}  
  
</script>