简体   繁体   English

在JQuery / Ajax中刷新后清除或重置下拉菜单的选项

[英]clear or reset options of dropdown after refresh in JQuery/Ajax

How can I clear the options of select box after refresh ... I have two select boxes and both of their values after refresh didn't clear or reset i am working in code igniter here is my code. 刷新后如何清除选择框的选项...我有两个选择框,刷新后它们的两个值都没有清除或重置,我正在代码点火器中工作,这是我的代码。

    <?php echo form_dropdown('cat_id', $records2, '#', 'class="cho" id="category"');?>


 <script type="text/javascript">// 
 $(document).ready(function(){       
    $('#category').change(function(){        
        $("#items > option").remove(); //it is not working
        var category_id = $('#category').val();  
        $.ajax({
            type: "POST",
            url: "testController/get_items/"+category_id,

            success: function(items)
            {
                $.each(items,function(item_id,item_name) 
                {
                    var opt = $('<option />'); 
                    opt.val(item_id);
                    opt.text(item_name);
                    $('#items').append(opt); 
                });
            }

        });

    });
});
// ]]>

try 尝试

 $("#items").empty();

empty() method will clear all html empty()方法将清除所有html

API Reference http://api.jquery.com/empty API参考http://api.jquery.com/empty

$('#items')
    .find('option')
    .remove()
    .end();

IE6 IE6

$('#items')
    .empty();

Instead of 代替

$("#items > option").remove(); //it is not working

try this 尝试这个

$("#items).html("");

Here is simple jsFiddle for you 是适合您的简单jsFiddle

UPDATE: 更新:

You might also consider to build you options markup first and then replace it at once, rather then sequentially append items. 您可能还考虑先构建选项标记,然后立即替换它,而不是顺序附加项目。

$("#category").change(function(){        
    var category_id = $("#category").val();  
    $.ajax({
        type: "POST",
        url: "testController/get_items/" + category_id,
        success: function(items)
        {
            var options = "";
            $.each(items, function(item_id, item_name) 
            {
                options += "<option value=\"" + item_id + "\">" + item_name + "</option>";
            });
            $("#items").html(options);
        }
    });
});

There is nothing in the document.ready event handler. document.ready事件处理程序中没有任何内容。 Everything is contained within $('#category').change(function(){ meaning nothing will happen on page refresh. 一切都包含在$('#category')。change(function(){中,这意味着页面刷新不会发生任何事情。

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

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