在隐藏文本框时删除文本框的内容

时间:2016-09-16 20:43:53

标签: javascript jquery html forms textbox

我有一个html程序,其中有一个清单。当我单击核对表中的某个项目时,它会显示一个文本框,当我取消选中该项目时,文本框会隐藏。如何设置它以便在取消选中项目时清除复选框的内容,或者至少将文本框引用的id值设置为空值?

以下是我的代码:

gotoxy()

2 个答案:

答案 0 :(得分:0)

您可以使用$(ITEM_SELECTOR).val('');

删除文字输入的值

查看代码,您可以修改看起来像

的每一行
else
    $(this).next('div.other').hide();
}).change();

else {
    $(this).next('div.other').hide();
    $(this).next('div.other').find('input[type=text]').val('');
}
}).change();

我会改变整个事情并通过围绕每个HTML元素组执行类似的操作来减少JS代码的数量:

<div class="form_field">
    <input type="checkbox" id="notification_1" value="Billing" class="toggle_cb" name="master">Billing
    <div class="master">
        <input type="text" id="notification_1_info" name="master">
    </div>
</div>

注意HTML块周围的.form_field容器。这有助于使事情变得更好,并在jQuery中为您提供更多导航选项(一切都在该父项下统一)。我会为每个项目执行此操作,然后将javascript更改为一个块,如下所示:

jQuery(document).ready(function($) {

    $('div.form_field > input[type=checkbox]').change(function(){
        if ($(this).is(':checked')) {
            $(this).next('div').show();
        }
        else {
            $(this).next('div').hide()
                .find('input[type=text]').val('');
        }
    }).change();
});

这会改变您必须编写(或重写)的代码量,这是一种尝试采用的良好思维方式。

答案 1 :(得分:0)

你可以试试这个:

$(document).ready(function() {
    function changeElement(element, type) {
        element.on('change', function() {
            if ($(this).is(':checked')) {
                $(this).next('div.' + type).show();

                return;
             }

            $(this).next('div.' + type).hide();
            $(this).find('input[name=' + type + ']').val('');
        });
    }

    changeElement($('input.master_enable_cb'), 'master');
    changeElement($('input.address_enable_cb'), 'address');
    changeElement($('input.phone_enable_cb'), 'phone');
    changeElement($('input.other_enable_cb'), 'other');

});
相关问题