문제

jQuery를 사용하면 선택 메뉴에서 선택한 옵션이 있는지 확인하고 그렇지 않은 경우 선택한 옵션 중 하나를 할당하십시오.

(방금 상속 한 앱에서 SELECT는 PHP 기능의 미로로 생성되므로 이것은 머리를 둘러싼 머리를 빠르게 해결하는 동안 빠른 수정입니다. :)

도움이 되었습니까?

해결책

당신이 달성하고자하는 것이 정확히 확실하지 않지만,이 코드는 저에게 효과적이었습니다.

<select id="mySelect" multiple="multiple">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">Fourth</option>
</select>

<script type="text/javascript"> 
$(document).ready(function() {
  if (!$("#mySelect option:selected").length) {
    $("#mySelect option[value='3']").attr('selected', 'selected');
  }
});
</script>

다른 팁

jQuery를 사용할 필요가 없습니다.

var foo = document.getElementById('yourSelect');
if (foo)
{
   if (foo.selectedIndex != null)
   {
       foo.selectedIndex = 0;
   } 
}

이 질문은 오래되었고 많은 견해를 가지고 있으므로, 나는 내가 확실한 사람들에게 도움이 될만한 물건을 버릴 것입니다.

선택된 요소에 선택된 항목이 있는지 확인하려면 다음과 같습니다.

if ($('#mySelect option:selected').length > 0) { alert('has a selected item'); }

또는 선택에 선택되지 않은지 확인하려면 다음과 같습니다.

if ($('#mySelect option:selected').length == 0) { alert('nothing selected'); }

또는 어떤 종류의 루프에 있고 현재 요소가 선택되었는지 확인하려는 경우 :

$('#mySelect option').each(function() {
    if ($(this).is(':selected')) { .. }
});

루프에있는 동안 요소가 선택되지 않은지 확인하려면 :

$('#mySelect option').each(function() {
    if ($(this).not(':selected')) { .. }
});

이것들은 이것을하는 몇 가지 방법입니다. jQuery는 같은 것을 달성하는 여러 가지 방법을 가지고 있으므로 일반적으로 가장 효율적인 것으로 보이는 것을 선택합니다.

Lencioni의 대답 내가 추천하는 것입니다. 옵션의 선택기를 변경할 수 있습니다 ('#mySelect option:last') "를 사용하여 특정 값으로 옵션을 선택하려면"#mySelect option[value='yourDefaultValue']". 선택기에 대한 자세한 내용.

클라이언트에서 Select Lists에서 광범위하게 작업하는 경우이 플러그인을 확인하십시오.http://www.texotela.co.uk/code/jquery/select/. Select Lists로 작업하는 몇 가지 예를보고 싶다면 소스를 살펴보십시오.

다음은 선택한 옵션을 변경하는 기능입니다. jQuery 1.3.2에서 작동합니다

function selectOption(select_id, option_val) {
    $('#'+select_id+' option:selected').removeAttr('selected');
    $('#'+select_id+' option[value='+option_val+']').attr('selected','selected');   
}
<script type="text/javascript"> 
$(document).ready(function() {
  if (!$("#mySelect option:selected").length)
   $("#mySelect").val( 3 );

});
</script>

쉬운! 기본값이 첫 번째 옵션이어야합니다. 완료! JavaScript가 필요하지 않기 때문에 눈에 띄지 않는 JavaScript로 이어질 것입니다. :)

눈에 띄지 않는 JavaScript

나는 이미 만났다 Texotela 플러그인 언급하면 다음과 같이 해결할 수 있습니다.

$(document).ready(function(){
    if ( $("#context").selectedValues() == false) {
    $("#context").selectOptions("71");
    }
});

를보세요 선택된 indexselect 요소. BTW, 그것은 jQuery-specific이 아닌 평범한 ol 'dom입니다.

이것은 내가 발견 한 빠른 스크립트였습니다 ....Result는 레이블에 할당됩니다.

$(".Result").html($("option:selected").text());

너희들은 선택하기에는 너무 많은 일을하고있다. 값으로 선택하십시오.

$("#mySelect").val( 3 );
if (!$("#select").find("option:selected").length){
  //
}

옵션이 선택된 경우 확인하는 좋은 방법을 찾았고 그렇지 않은 경우 기본값을 선택합니다.

    if(!$('#some_select option[selected="selected"]').val()) {
        //here code if it HAS NOT selected value
        //for exaple adding the first value as "placeholder"
        $('#some_select option:first-child').before('<option disabled selected>Wybierz:</option>');
    }

만약에 #some_select 그렇다면 기본값 선택 옵션이 없습니다 .val () ~이다 한정되지 않은

$("option[value*='2']").attr('selected', 'selected');
// 2 for example, add * for every option
$("#select_box_id").children()[1].selected

이것은 jQuery에서 옵션이 선택되었는지 확인하는 또 다른 방법입니다. 이것은 부울 (참 또는 거짓)을 반환합니다.

1]은 선택 상자 옵션의 색인입니다

선택 상자에서 이벤트를 발사하고 일단 선택한 옵션의 ID 속성을 가져 오면 다음과 같습니다.

$("#type").change(function(){
  var id = $(this).find("option:selected").attr("id");

  switch (id){
    case "trade_buy_max":
      // do something here
      break;
  }
});

I was just looking for something similar and found this:

$('.mySelect:not(:has(option[selected])) option[value="2"]').attr('selected', true);

This finds all select menus in the class that don't already have an option selected, and selects the default option ("2" in this case).

I tried using :selected instead of [selected], but that didn't work because something is always selected, even if nothing has the attribute

If you need to explicitly check each option to see if any have the "selected" attribute you can do this. Otherwise using option:selected you'll get the value for the first default option.

var viewport_selected = false;      
$('#viewport option').each(function() {
    if ($(this).attr("selected") == "selected") {
        viewport_selected = true;
    }
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top