javascript 如何使用jquery重置表单中的多个选择框?

gopyfrb3  于 2023-08-02  发布在  Java
关注(0)|答案(7)|浏览(94)

如何使用jquery重置表单中的多个选择框?

  • 有多个选择框
  • 它们是动态生成的&我们不知道它们会是什么
  • 某些框选项标记将被标记为选中
  • 小提琴:http://jsfiddle.net/Qnq82/

我有这个到目前为止,它重置一切,但选择。

$('button#reset').click(function(){
    $form = $('button#reset').closest('form');
    $form.find('input:text, input:password, input:file, select, textarea').val('');
    $form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
    $form.find('select').selectedIndex = 0;
  });

字符串

添加了一些标记:

<form id="form" name="form" method="post" class="form" role="form" action="inventory-search" enctype="multipart/form-data">

    <div class="form-group">
        <label for="grade">Grade</label>
        <select name="grade" class="form-control input-sm" onchange="this.form.submit();">
            <option value="">Any</option>
            <option value="opt1">opt1</option>
            <option value="opt2" selected="selected">opt2</option>

        </select>
    </div>

    <!-- there are 6 more select controls -->

    <div class="form-group">
        <label>&nbsp;</label>
        <button type="submit" name="search" id="search" value="search" class="btn button-sm btn-primary">Search</button>
    </div>

    <div class="form-group">
        <label>&nbsp;</label>
        <button type="reset" name="reset" id="reset" value="reset" class="btn button-sm btn-primary">Reset</button>
    </div>

</form>

9wbgstp7

9wbgstp71#

这将工作:-

$form.find('select').prop('selectedIndex',0);

字符串

sg2wtvxw

sg2wtvxw2#

我用下面的代码成功地取消了表单中的所有html选择:

$("#form1").find('select').prop('selectedIndex', -1);

字符串

e4yzc0pl

e4yzc0pl3#

我在StackOverFlow上搜索了很多,但是没有找到任何重置多选的解决方案。然后我找到了This Link。这解决了我的问题。下面是代码示例。

$("#yourcontrolid").multiselect('clearSelection');

字符串

xxslljrj

xxslljrj4#

将最后一行更改为:

$form.find('select')[0].selectedIndex = 0;

字符串
selectedIndexHTMLElement的属性,而不是jQuery对象。
如果你知道这个值,那么你可以做$form.find('select').val('value');

voase2hg

voase2hg5#

下面的代码为我工作:

$('.formID').find('select[id="selectID1"]').removeAttr('selected').trigger('change');
$('.formID').find('select[id="selectID2"]').removeAttr('selected').trigger('change');

字符串

uoifb46i

uoifb46i6#

$form.find('select').each(function(){
    $(this).val($(this).find('option:first').val());
});

字符串
这个对我有用

cyvaqqii

cyvaqqii7#

当我遇到这个问题时,我一直在研究,但没有一个答案对我有用。然而,以防万一有其他人在同一时间内访问这个问题,我找到了答案。

$("#id option:selected").prop("selected", false);

字符串
或者

$("#id").val([]);


这两种方法对我都很有效,从选择字段中清除所有选定的值,无论它是否具有multiple属性。

相关问题