I have a dynamic dropdown. That populates the second drop down. My javascript is not taking my variables when I change my selection when I tested with one php variable. Am new to this
Javascript:
<script type="text/javascript">
function populate(s1,s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if(s1.value=="<?php echo $car; ?>"){
var optionArray=[" ","camero Camaro","convette Convette"];
} else
if(s1.value=="Dodge"){
var optionArray=[" ","avanger Avanger","challenger Challenger"];
} else if(s1.value=="Ford"){
var optionArray=[" ","mustang Mustang","fiesta Fiesta"];
}
for (var option in optionArray){
var pair = optionArray[option].split(" ");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
</script>
PHP file:
<select name="slct1" id="slct1" onchange="populate(this.id,'slct2')">
<option value=""></option>
<option value="<?php $car = 'Chevy';echo $car; ?>">Chevy</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
<hr />
<select id="slct2" name="slct2">
</select>
<hr />
It is because you assign a variable <?php $car = 'Chevy'; ?>
You need to print it <?php echo 'Chevy'; ?>
or <?php echo $car; ?>
<option value="<?='Chevy'?>">Chevy</option>
This
if(s1.value=="<?php echo $car; ?>"){
Will be parsed and the value of $car will be added.
<option value="<?php $car = 'Chevy'; ?>">Chevy</option>
Replace it with
<option value="<?php $car = 'Chevy'; echo $car; ?>">Chevy</option>
And remember to assign something to $car. As i said above,
if(s1.value=="<?php echo $car; ?>"){
will be parsed, add $car = 'Chevy'; above it
If the javascript code you show is in a *.js file the inline php in it will not be parsed by php.
I can't tell if that is the problem you are having or if it is something deeper. When the javascript is sent to your browser does line 6 look like:
if(s1.value=="<?php echo $car; ?>"){
or
if(s1.value=="Chevy"){
if it looks like the first one, but you want it to look like the second one then you need to have your javascript be in the php file so it has access to your variables.
Problem is int this line
if(s1.value=="<?php echo $car; ?>"){
Try using hidden input tag of html
<input id="hidden_field" name="hidden_field" type="hidden" value="<?php echo $car;?>" />
and in Javascript
var hidden_Value = document.getElementById('hidden_field').value;
if(s1.value==hidden_Value ){