【问题标题】:Reset the Value of a Select Box重置选择框的值
【发布时间】:2012-09-26 02:16:41
【问题描述】:

我正在尝试重置两个选择字段的值,结构如下,

<select>
  <option></option>
  <option></option>
  <option></option>
</select>

<select>
  <option></option>
  <option></option>
  <option></option>
</select>

jQuery,

$('select').each(function(idx, sel) {
  $(sel).find('option :eq(0)').attr('selected', true);
});

不幸的是,无论我尝试多少方法,它都不会发生。控制台中什么都没有。我不知道是怎么回事?我知道必须有办法做到这一点,你可以用 JS 做 任何事情

编辑:

我发现只有当我尝试在单击 dom 元素时触发代码时才会出现问题,但是,我知道代码应该可以工作,因为当我有

$('p').click(function(){
  console.log('test');
});

它将“测试”输出到控制台,但是当我在此函数中包含代码时,什么也没有发生。这是为什么呢?

【问题讨论】:

  • 您是否尝试过使用“val()”进行重置?
  • 嗯...你的代码对我有用。
  • 你应该编码find('option:eq(0)')而不是find('option :eq(0)')
  • 该代码将设置每个选择的第一个选项的选定属性。它不会从其他可能具有该属性的选项中删除该选定属性(因此两个选项可能具有该选定属性,这可能会在多个选择元素中产生意外结果)。此外,它不一定会选择选项,因为 selected 属性仅设置默认选择哪个选项,而不是当前选择哪个选项。某些浏览器确实将其设为当前选择的选项,而其他浏览器则不会。
  • 点击here查看我对此主题的回答或访问:stackoverflow.com/a/46196428/6016078

标签: javascript jquery


【解决方案1】:

使用.val('') 设置器

jsfiddle example

$('select').val('1');

【讨论】:

  • 只有当第一个选项的值为"1"时才有效。
【解决方案2】:

这对我有用:

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

FIDDLE

【讨论】:

    【解决方案3】:

    不久前我发现了一个小实用函数,从那以后我就一直用它来重置我的表单元素(来源:http://www.learningjquery.com/2007/08/clearing-form-data):

    function clearForm(form) {
      // iterate over all of the inputs for the given form element
      $(':input', form).each(function() {
        var type = this.type;
        var tag = this.tagName.toLowerCase(); // normalize case
        // it's ok to reset the value attr of text inputs, 
        // password inputs, and textareas
        if (type == 'text' || type == 'password' || tag == 'textarea')
          this.value = "";
        // checkboxes and radios need to have their checked state cleared 
        // but should *not* have their 'value' changed
        else if (type == 'checkbox' || type == 'radio')
          this.checked = false;
        // select elements need to have their 'selectedIndex' property set to -1
        // (this works for both single and multiple select elements)
        else if (tag == 'select')
          this.selectedIndex = -1;
      });
    };
    

    ...或作为 jQuery 插件...

    $.fn.clearForm = function() {
      return this.each(function() {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (tag == 'form')
          return $(':input',this).clearForm();
        if (type == 'text' || type == 'password' || tag == 'textarea')
          this.value = '';
        else if (type == 'checkbox' || type == 'radio')
          this.checked = false;
        else if (tag == 'select')
          this.selectedIndex = -1;
      });
    };
    

    【讨论】:

    • 你为什么要这样做而不是简单地form.reset()?特别是因为上面忽略了默认值。
    • 我想我更多的是采用“清​​除形式”方法而不是“重置形式”方法。我不确定用户在寻找哪个...
    【解决方案4】:

    我假设您只想重置单个元素。重置整个表单很简单:调用它的 reset 方法。

    “重置”选择元素的最简单方法是将其selectedIndex 属性设置为默认值。如果您知道没有选项是默认选择的选项,只需将选择元素的 selectedIndex 属性设置为适当的值:

    function resetSelectElement(selectElement) {
        selecElement.selectedIndex = 0;  // first option is selected, or
                                         // -1 for no option selected
    }
    

    但是,由于一个选项可能具有选定的属性或以其他方式设置为默认选定选项,因此您可能需要执行以下操作:

    function resetSelectElement(selectElement) {
        var options = selectElement.options;
    
        // Look for a default selected option
        for (var i=0, iLen=options.length; i<iLen; i++) {
    
            if (options[i].defaultSelected) {
                selectElement.selectedIndex = i;
                return;
            }
        }
    
        // If no option is the default, select first or none as appropriate
        selectElement.selectedIndex = 0; // or -1 for no option selected
    }
    

    并且要注意设置属性而不是属性,它们在不同的浏览器中具有不同的效果。

    【讨论】:

      【解决方案5】:

      除了@RobG 的纯/香草 javascript 答案,您可以重置为“默认”值

      selectElement.selectedIndex = null;
      

      似乎-1取消选择所有项目,null选择默认项目,0或正数选择相应的索引选项。

      选择对象中的选项按照定义的顺序进行索引,从索引 0 开始。

      source

      【讨论】:

        【解决方案6】:

        对我有用的是:

        $('select option').each(function(){$(this).removeAttr('selected');});   
        

        【讨论】:

          【解决方案7】:

          neRok 提到了上面的这个答案,我只是在扩展它。

          根据稍微过时但方便的 O'Reilly 参考书,Javascript: The Definitive Guide

          Select 对象的 selectedIndex 属性是一个整数,它指定 Select 对象中选定选项的索引。如果未选择任何选项,则 selectedIndex 为 -1。

          因此,以下 javascript 代码会将 Select 对象“重置”为未选择任何选项:

          select_box = document.getElementById("myselectbox");
          select_box.selectedIndex = -1;
          

          请注意,以这种方式更改选择不会触发 onchange() 事件处理程序。

          【讨论】:

            【解决方案8】:

            不使用 javaScript 的最简单方法是将所有

            <form>
              <select>
                <option>one</option>
                <option>two</option>
                <option selected>three</option>
              </select>
              <input type="reset" value="Reset" />
            </form>
            

            或者,使用 JavaScript,可以通过以下方式完成:

            HTML 代码:

            <select>
              <option selected>one</option>
              <option>two</option>
              <option>three</option>
            </select>
            <button id="revert">Reset</button>
            

            还有 JavaScript 代码:

            const button = document.getElementById("revert");
            const options = document.querySelectorAll('select option');
            button.onclick = () => {
              for (var i = 0; i < options.length; i++) {
                options[i].selected = options[i].defaultSelected;
              }
            }
            

            如果您有多个选定的项目或单个选定的项目,这两种方法都将起作用。

            【讨论】:

              【解决方案9】:

              选择2

              $('select').select2().val('').trigger('change');
              

              如果你想重置,只需选择表单中的 2 个元素

              $("#formId").find('select').select2().val('').trigger('change');
              

              【讨论】:

                猜你喜欢
                • 2023-02-16
                • 2013-08-10
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2022-06-28
                • 1970-01-01
                • 2021-03-09
                • 1970-01-01
                相关资源
                最近更新 更多