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

时间:2014-07-16 02:34:12

标签: javascript jquery

如何使用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>

6 个答案:

答案 0 :(得分:4)

这将有效: -

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

答案 1 :(得分:2)

您可以使用此代码成功选择表单中的所有html选择:

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

答案 2 :(得分:1)

我在StackOverFlow上试了很多但是没有得到任何重置multiselect的解决方案。然后我找到了This Link。这解决了我的问题。 这是代码示例。

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

答案 3 :(得分:0)

将最后一行更改为:

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

selectedIndexHTMLElement的属性,而不是jQuery对象。

如果您知道该值,则可以执行$form.find('select').val('value');

答案 4 :(得分:0)

以下代码对我有用:

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

答案 5 :(得分:0)

import re
def mapFileToCount(s):
    words = re.split("\s+", s)
    up = 0
    for word in words:
        if word and word[0].isupper():
            up = up + 1
    return up

这个对我有用...