37

このように構成された2つの選択フィールドの値をリセットしようとしています。

<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');
});

'test'をコンソールに出力しますが、この関数にコードを含めると何も起こりません。どうしてこれなの?

4

9 に答える 9

57

1つの要素だけをリセットしたいと思います。フォーム全体のリセットは簡単です。resetメソッドを呼び出します。

選択要素を「リセット」する最も簡単な方法は、そのselectedIndexプロパティをデフォルト値に設定することです。デフォルトで選択されているオプションがないことがわかっている場合は、selectelemen'tsselectedIndexプロパティを適切な値に設定するだけです

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

ただし、1つのオプションに選択された属性があるか、デフォルトの選択されたオプションに設定されている可能性があるため、次のことを行う必要があります。

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
}

また、プロパティではなく属性を設定することに注意してください。属性はブラウザによって効果が異なります。

于 2012-10-05T01:31:46.710 に答える
28

これは私のために働きます:

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

フィドル

于 2012-10-05T00:13:43.930 に答える
9

@RobGの純粋な/バニラJavaScriptの回答に加えて、次のようにして「デフォルト」値にリセットできます。

selectElement.selectedIndex = null;

-1はすべてのアイテムの選択を解除し、nullはデフォルトのアイテムを選択し、0または正の数は対応するインデックスオプションを選択するようです。

selectオブジェクトのオプションは、インデックス0から始まり、定義された順序でインデックスが付けられます。

ソース

于 2014-07-09T03:54:16.733 に答える
8

neRokは上記のこの答えに触れました、そして私はちょうどそれを拡大しています。

少し古いが便利なO'Reillyの参考書によると、Javascript:The Definitive Guide

SelectオブジェクトのselectedIndexプロパティは、Selectオブジェクト内の選択されたオプションのインデックスを指定する整数です。オプションが選択されていない場合、selectedIndexは-1です。

そのため、次のjavascriptコードは、Selectオブジェクトをオプションが選択されていない状態に「リセット」します。

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

この方法で選択を変更しても、onchange()イベントハンドラーはトリガーされないことに注意してください。

于 2017-11-17T19:34:41.460 に答える
1

.val('')セッターを使用する

jsfiddleの例

$('select').val('1');
于 2012-10-04T23:43:12.047 に答える
1

しばらく前に小さなユーティリティ関数を見つけ、それ以来、フォーム要素をリセットするためにそれを使用しています(ソース: 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;
  });
};
于 2012-10-05T00:17:58.767 に答える
1

私のために働いたのは:

$('select option').each(function(){$(this).removeAttr('selected');});   
于 2017-07-04T12:34:17.750 に答える
1

javaScriptを使用しない最も簡単な方法は、すべての<select>ドロップダウンを<form>タグ内に配置し、フォームリセットボタンを使用することです。例:

<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;
  }
}

複数の選択されたアイテムまたは単一の選択されたアイテムがある場合、これらの方法の両方が機能します。

于 2020-11-24T14:56:32.447 に答える
0

select2の場合

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

リセットしたい場合は、フォームのselect2要素だけを選択してください

$("#formId").find('select').select2().val('').trigger('change');
于 2021-11-29T13:08:19.893 に答える