我如何清除所有字段在一个可变的html内容?(最好使用jQuery)

How do I clear all the fields in a variable html content? (preferably with jQuery)

本文关键字:内容 html jQuery 清除 何清除 字段 一个      更新时间:2023-09-26

我需要重置保存在变量中的HTML内容中的所有表单字段。我在网上和这里都搜过了。但我找到的方法都还没用。即使使用最简单的方法来处理文本字段也不会成功:

var content = $(this).prev('.listset').find('ol.multiple > li:last').html();
$(content).find('input[type=text]').val('');

我没有可用的表单id

使用普通的javascript:

document.forms['my_form_name'].reset()

我发现了这个:

如果你的表单ID是myform:

$(':input','#myform')
 .not(':button, :submit, :reset, :hidden')
 .val('')
 .removeAttr('checked')
 .removeAttr('selected');

它正在使用:input选择器,它将匹配所有input, textarea, select和button元素。由于我们将#myform作为第二个参数传递,因此它只会在此表单元素中查找输入。然后,它使用not()过滤掉所有按钮、提交、重置和隐藏输入。然后它使用val()将其余字段的值设置为空字符串,然后它使用removeAttr删除字段的选中和选择属性,以防您有任何单选/复选框/选择输入。这样。

这里:用jQuery重置多级表单

编辑:从相同的url:如果你的复选框上也有默认值,那就用这个:

 // Use a whitelist of fields to minimize unintended side effects.
    $(':text, :password, :file, SELECT', '#myFormId').val('');  
    // De-select any checkboxes, radios and drop-down menus
    $(':input', '#myFormId').removeAttr('checked').removeAttr('selected');

这是你要找的吗?

如果使用所有文本框:

for(c in document.getElementById('id_of_form').childNodes) {
    c.innerHTML = "";
}

如果您使用多个内容,请将childNodes替换为getElementByTagName("标签的名称"),并将过滤器替换为type.

这是一个有点猜测,因为我不知道你的标记看起来像什么,但jQuery 'find'可能不工作取决于如何html字符串的结构-看看这个问题-

使用jQuery搜索HTML

你可以尝试遍历'content'字符串,然后单独更新每个表单元素并将它们添加到相关的容器中,例如-

$(content).each(function () {
   if (this.nodeName == 'INPUT') $(this).val('');
   if (this.nodeName == 'SELECT') $(this).children('option').prop('selected','');
   $("#moveto").append(this);
});

工作演示- http://jsfiddle.net/vFMWD/5/