0
votes

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;
?>
4
Your question isn't very clear.NaijaProgrammer
Sorry which part that is not clear to you? Please tell so that I can clarify it. many thanksGiang Nguyen
You have to populate the sub-category select menu with the returned ajax response. But to be able to help you out with that, I need to know the format of the returned response.NaijaProgrammer
HI I have just added the extra information about the ajax call and returned response.Giang Nguyen
I've updated my answer. Check out the code, should work for you.NaijaProgrammer

4 Answers

0
votes

You have to use

if ($(this).val() == 'sub-cat-one'){

instead of

if (subcat.val() == 'sub-cat-one'){

to access the correct html element (#subcat) in your onchange eventhandler.

You also shouldn't use the id subcat for more than one element. Currently the div and the select are having id subcat.

0
votes

You have two elements ( div and select ) with same id subcat. id attribute should be unique for all elements .

0
votes

I think you should try below suggestions:

  1. Use AJAX success callback instead of using onchange.
  2. if ($(this).val() == 'sub-cat-one')
0
votes

I think I see where your problem is coming from, on each iteration you echo the result. And only that result gets returned to your ajax script. Do this in your php file:

$returned_string = '[';

foreach($result as $row)
{
   $returned_string .= '{"name" : "'. $row[name]. '", "value" : "'. $row[name]. '"},';
}
$returned_string = substr($returned_string, 0, -1); //remove trailing ','
$returned_string .= ']';

header("Content-type: application/json");
echo $returned_string;
exit;

Then in your successCallback function:

xmlhttp.onreadystatechange=function()
{
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
      var response = JSON.parse(xmlhttp.responseText);
      var selectElement = document.getElementById('subcat');
      for(var i = 0; i < response.length; i++)
      {
         var idx = i+1;
         selectElement.options[idx] = new Option(response[idx].value, response[idx].name, false, false);
      }
    }
  }
}