【超簡単】jQueryでselect要素の最初のオプションをデフォルト選択にする
jQueryで最初のオプションをデフォルト選択にする方法
<select id="my-select">
<option value="">選択してください</option>
<option value="1">オプション 1</option>
<option value="2">オプション 2</option>
<option value="3">オプション 3</option>
</select>
方法1: :firstセレクター
$(document).ready(function() {
$('#my-select').find(':first').prop('selected', true);
});
このコードは、select
要素の子要素のうち、最初のオプション要素を選択状態にします。
方法2: eq()メソッド
$(document).ready(function() {
$('#my-select').eq(0).prop('selected', true);
});
$(document).ready(function() {
$('#my-select').val('');
});
このコードは、select
要素のvalue
属性を空("")に設定します。
補足
- 上記の例では、
$(document).ready(function() { ... });
を使用していますが、これはDOMContentLoadedイベントが発生した後にコードを実行するものです。 - これらの方法は、
select
要素に複数選択が許可されている場合にも使用できます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQueryで最初のオプションをデフォルト選択にする</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<select id="my-select">
<option value="">選択してください</option>
<option value="1">オプション 1</option>
<option value="2">オプション 2</option>
<option value="3">オプション 3</option>
</select>
<script>
$(document).ready(function() {
// 方法1: :firstセレクター
// $('#my-select').find(':first').prop('selected', true);
// 方法2: eq()メソッド
// $('#my-select').eq(0).prop('selected', true);
// 方法3: val()メソッド
$('#my-select').val('');
});
</script>
</body>
</html>
jQueryで最初のオプションをデフォルト選択にするその他の方法
$(document).ready(function() {
$('#my-select').find('option:first').attr('selected', 'selected');
});
$(document).ready(function() {
$('#my-select').find('option:first').prop('selected', true);
});
方法6: children()メソッド
$(document).ready(function() {
$('#my-select').children().first().prop('selected', true);
});
$(document).ready(function() {
$('#my-select').find('option[value=""]').prop('selected', true);
$(document).ready(function() {
$('#my-select').find('option').filter(':not(:disabled)').first().prop('selected', true);
});
これらの方法はすべて、同じ結果を達成します。どの方法を使用するかは、コードのスタイルや好みによって異なります。
jquery select