문제
jQuery로 선택한 첫 번째 옵션을 어떻게 만드나요?
<select id="target">
<option value="1">...</option>
<option value="2">...</option>
</select>
해결책
$("#target").val($("#target option:first").val());
다른 팁
당신은 이것을 시도 할 수 있습니다
$("#target").prop("selectedIndex", 0);
// remove "selected" from any options that might already be selected
$('#target option[selected="selected"]').each(
function() {
$(this).removeAttr('selected');
}
);
// mark the first option as selected
$("#target option:first").attr('selected','selected');
당신이 사용할 때
$("#target").val($("#target option:first").val());
첫 번째 옵션 값이 NULL 인 경우 Chrome 및 Safari에서는 작동하지 않습니다.
나는 선호한다
$("#target option:first").attr('selected','selected');
모든 브라우저에서 작동 할 수 있기 때문입니다.
선택 입력의 값을 변경하거나 선택한 속성을 조정하면 DOM 요소의 기본 선택 탑재 속성을 덮어 쓸 수 있으므로 재설정 이벤트가 호출 된 양식에서 제대로 재설정되지 않을 수 있습니다.
JQuery의 소품 메소드를 사용하여 필요한 옵션을 지우고 설정하십시오.
$("#target option:selected").prop("selected", false);
$("#target option:first").prop("selected", "selected");
$("#target")[0].selectedIndex = 0;
하나의 미묘한 지점 i 생각한다 나는 최상위에 대한 대답에 대해 발견했지만 선택한 값을 올바르게 변경하더라도 사용자가 보는 요소를 업데이트하지 않는다는 것입니다 (위젯을 클릭하면 업데이트 된 요소 옆에 확인이 표시됩니다).
changing a .change () 끝으로 전화하면 UI 위젯도 업데이트됩니다.
$("#target").val($("#target option:first").val()).change();
(jQuery Mobile과 Chrome 데스크탑에서 상자를 사용하는 동안 이것을 발견 했으므로 어디에서나 그렇지 않을 수 있습니다).
옵션이 비활성화 된 경우 추가 할 수 있습니다 NOT ([장애인]) 다음과 같은 결과를 선택하는 것을 방지하려면 다음과 같습니다.
$("#target option:not([disabled]):first").attr('selected','selected')
값을 재설정하는 또 다른 방법 (여러 선택된 요소의 경우)은 다음과 같습니다.
$("selector").each(function(){
/*Perform any check and validation if needed for each item */
/*Use "this" to handle the element in javascript or "$(this)" to handle the element with jquery */
this.selectedIndex=0;
});
$('#newType option:first').prop('selected', true);
그 간단한 :
$('#target option:first').prop('selected', true);
선택한 속성이 이미 있으면 attr을 설정하는 것이 작동하지 않는다는 것을 알았습니다. 지금 사용하는 코드는 먼저 선택한 속성을 설정 한 다음 첫 번째 옵션을 선택합니다.
$('#target').removeAttr('selected').find('option:first').attr('selected', 'selected');
다음은 다음과 같습니다.
$("#target option")
.removeAttr('selected')
.find(':first') // You can also use .find('[value=MyVal]')
.attr('selected','selected');
각 기능은 아마도 필요하지 않지만 ...
$('select').each(function(){
$(this).find('option:first').prop('selected', 'selected');
});
나를 위해 일합니다.
다음과 같이 마지막에 트리거 ( 'Change')를 사용하여 나에게만 효과가있었습니다.
$("#target option:first").attr('selected','selected').trigger('change');
첫 번째 옵션을 기본값으로 사용하려는 경우
<select>
<option value="">Please select an option below</option>
...
그런 다음 사용할 수 있습니다.
$('select').val('');
멋지고 간단합니다.
James Lee Baker의 답변 뒤에서, 나는이 솔루션이 브라우저 지원에 대한 의존성을 제거하므로 다음을 선호합니다 : 첫 번째 : 선택된 ...
$('#target').children().prop('selected', false);
$($('#target').children()[0]).prop('selected', 'selected');
나에게는 다음 코드를 추가했을 때만 작동했습니다.
.change();
나에게는 다음 코드를 추가 할 때만 작동했습니다. 양식을 "재설정"하고 싶었 기 때문에 양식의 모든 선택의 첫 번째 옵션을 모두 선택했습니다. 다음 코드를 사용했습니다.
$('form').find('select').each(function(){
$(this).val($("select option:first").val());
$(this).change();
});
$("#target").val(null);
크롬에서 잘 작동했습니다
선택 요소의 jQuery 객체를 저장하는 경우 :
var jQuerySelectObject = $("...");
...
jQuerySelectObject.val(jQuerySelectObject.children().eq(0).val());
jQuery를 사용 하여이 최상의 접근 방식을 확인하십시오 ECMAScript 6:
$('select').each((i, item) => {
var $item = $(item);
$item.val($item.find('option:first').val());
});
나에게는 다음 코드 줄을 추가했을 때만 작동했습니다.
$('#target').val($('#target').find("option:first").val());
옵션을 선택할 수 있습니다 dropdown
그것을 사용함으로써.
// 'N' can by any number of option. // e.g., N=1 for first option
$("#DropDownId").val($("#DropDownId option:eq(N-1)").val());
$('select#id').val($('#id option')[index].value)
교체 ID 특정 태그 ID와 특히 선택합니다 인덱스 특정 요소로 선택하려는 요소가 있습니다.
즉
<select class="input-field" multiple="multiple" id="ddlState" name="ddlState">
<option value="AB">AB</option>
<option value="AK">AK</option>
<option value="AL">AL</option>
</select>
따라서 첫 번째 요소 선택의 경우 다음 코드를 사용합니다.
$('select#ddlState').val($('#ddlState option')[0].value)
이것은 나를 위해 효과가있었습니다!
$("#target").prop("selectedIndex", 0);
사용:
alert($( "#target option:first" ).text());