I have this form which has one select field for main-category, one select field for sub-category and a hidden field. This hidden field is only displayed when a specific value chosen from sub-category.
This sub-category options are the result of ajax response from main-category. Here is the form:
<form>
<select id='main-cat' name='maincat' onchange="sortSubcat(this.value)"/>
<option value="">Please select one category</option>
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 3</option>
</select>
<div id='subcat-more'>
<select id='subcat' name='subcat'>
<option value=''>Please select a subcategory</option>
</select>
</div>
<div id='morefield' style='display:none'>
<input type='text' name='option1'/>
</div>
</form>
I have a Jquery code which handle this form validation, and it tells whether the #morefield is displayed or not. Here is part of this code:
$("#subcat").change(function(){
if (subcat.val() == 'sub-cat-one'){
$("#morefield").css("display","block");
}else{
$("#morefield").hide();
}
});
Unfortunately, Ajax response only displays option on screen however, it did not change in html so when I viewed source code, I don't see any option for sub-cat. Thats why even I chose option sub-cat-one, I would show the div #morefield.
Is there anyway to solve this problem?
Best Regards,
More informaiton:
Here is my ajax call:
function sortSubcat(str)
{
if (str=="")
{
document.getElementById("subcat").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("subcat").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/member/sortsubcat.php?q="+str,true);
xmlhttp.send();
}
Here is the php file:
<?php
require_once("../configs/dbconnect.php");
if (!empty($_GET['q'])){
$q = basename($_GET['q']);
$sql="SELECT * FROM subcat WHERE maincat=:q";
$result = $conn->prepare($sql);
$result->bindParam(':q', $q);
$result->execute();
echo "<option value=''>Please select a sub cat</option>";
foreach($result as $row)
{
echo "<option value='$row[name]'>$row[name]</option>";
}
}
else{
echo "<option value=''>Please select a subcat</option>";
}
$conn=null;
?>