Anandhu
Anandhu

Reputation: 67

How can we set options in select tag using jquery

I have two drop-down in my ui page. The second drop-down is generated when I select the first one.Here is my html code

  <td width="100"><label for="type">Menu Category Name:</label></td>
        <td width="200">
            <select name="type" id="type" class="target dropdown required"  onchange = getSubCategory(); tabindex="3" >
                <?php echo $typeOption;?>
            </select>
        </td>


<tr height="50">    
        <td width="100"><label for="sub_type">Menu Sub Category Name:</label></td>
        <td width="200">
            <select name="sub_type" id="sub_type" class="sub dropdown required" tabindex="3" >

            </select>
        </td>

    <tr height="50">

And my getSubCategory() function is

function getSubCategory(){
alert($("#type").val());
var catId = $("#type").val();
ajax(url,{id:catId,action:"getAllSubcategory"},function (response){
    $("div.sub").val(response);

});

}

and this is my backend php code.Here I am setting every option

function getAllSubcategory(){
global $db;
$data = $_REQUEST;
$getProductSubType = "SELECT id, name FROM cp_reference_master WHERE active = 'Y' 
                   AND mode='item_type_subcat'AND parent_id = '".$data['id']."' ORDER BY name ASC";
$resultType = $db->func_query($getProductSubType);

$subTypeOption = '<option value="">Select Category</option>';
$subTypeList = array();
if(is_array($resultType) && count($resultType)>0){
    foreach($resultType as $key => $details){
        $subTypeOption .= '<option value="'.$details['id'].'">'.$details['name'].'</option>';
        $subTypeList[$details['id']] = $details['name'];
    }
}
 return $subTypeOption;

}

I need to set the response to my subcategory select tag. I am unable to set the same. What is wrong in my code. I have tried 2 or 3 solutions already.

Upvotes: 1

Views: 123

Answers (1)

Amin Jafari
Amin Jafari

Reputation: 7207

you need to use append() or html() instead of val()

also you do not have a div.sub element in the code you've shown us, so I assume you want to add the response to the second select tag:

function getSubCategory(){
    var catId = $("#type").val();
    ajax(url,{id:catId,action:"getAllSubcategory"},function (response){
        $("#sub_type").append(response);
    });
});

Upvotes: 3

Related Questions