简体   繁体   English

我们如何使用jquery在select标签中设置选项

[英]How can we set options in select tag using jquery

I have two drop-down in my ui page. 我的ui页面中有两个下拉列表。 The second drop-down is generated when I select the first one.Here is my html code 当我选择第一个下拉列表时会生成第二个下拉列表。这是我的html代码

  <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 我的getSubCategory()函数是

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 这是我的后端php代码。我在设置每个选项

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. 我已经尝试过2或3种解决方案。

you need to use append() or html() instead of val() 你需要使用append()html()而不是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: 你在我们展示的代码中也没有div.sub元素,所以我假设你想要将响应添加到第二个select标签:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM