programing tip

jQuery를 사용하여 선택 상자에서 첫 번째 옵션을 설정하는 방법은 무엇입니까?

itbloger 2020. 6. 29. 08:12
반응형

jQuery를 사용하여 선택 상자에서 첫 번째 옵션을 설정하는 방법은 무엇입니까?


두 개의 HTML select상자가 있습니다. 다른 select상자에서 선택할 때 상자 를 재설정해야합니다 .

<select id="name" >
    <option value="">select all</option>
    <option value="1">Text 1</option>
    <option value="2">Text 2</option>
    <option value="3">Text 3</option>
</select>

<select id="name2" >
    <option value="">select all</option>
    <option value="1">Text 1</option>
    <option value="2">Text 2</option>
    <option value="3">Text 3</option>
</select>

첫 번째 옵션 select(예 :)을 선택 id="name"하면 두 번째 옵션 selectselect all; 마찬가지로 두 번째 옵션 select(예 id="name2":)을 선택하면 첫 번째 옵션을 로 재설정해야 select합니다 select all.

어떻게해야합니까?


이와 같은 것이 트릭을 수행해야합니다 : https://jsfiddle.net/TmJCE/898/

$('#name2').change(function(){
    $('#name').prop('selectedIndex',0);
});


$('#name').change(function(){
    $('#name2').prop('selectedIndex',0);
});

select 요소를 첫 번째 위치로 재설정하려는 경우 가장 간단한 방법은 다음과 같습니다.

$('#name2').val('');

문서에서 모든 선택된 요소를 재설정하려면

$('select').val('')

편집 : 아래 주석에 따라 명확히하기 위해 목록에 빈 항목이있는 경우에만 선택 요소를 첫 번째 빈 항목으로 재설정합니다.


의견에서 @PierredeLESPINAY가 지적한 것처럼 원래의 솔루션은 올바르지 않습니다. 드롭 다운을 최상위 옵션으로 재설정하지만 undefined반환 값이 색인 0으로 해석 되었기 때문에 가능합니다 .

다음은 selected속성을 고려한 올바른 솔루션입니다 .

$('#name').change(function(){
    $('#name2').val(function () {
        return $(this).find('option').filter(function () {
            return $(this).prop('defaultSelected');
        }).val();
    });
});

데모 : http://jsfiddle.net/weg82/257/


원래 답변-INCORRECT

jQuery 1.6 이상에서는 .prop기본 선택을 위해 메소드를 사용해야합니다 .

// Resets the name2 dropdown to its default value
$('#name2').val( $('#name2').prop('defaultSelected') );

첫 번째 드롭 다운이 변경 될 때 동적으로 재설정되도록하려면 다음 .change이벤트를 사용하십시오 .

$('#name').change(function(){
  $('#name2').val( $('#name2').prop('defaultSelected') );
});

"selected"속성이있는 옵션으로 선택을 재설정하려면이 옵션을 사용하십시오. form.reset () 내장 자바 스크립트 함수와 유사하게 선택합니다.

 $("#name").val($("#name option[selected]").val());

이것은 나를 많이 도와줍니다.

$(yourSelector).find('select option:eq(0)').prop('selected', true);

Here is how I got it to work if you just want to get it back to your first option e.g. "Choose an option" "Select_id_wrap" is obviously the div around the select, but I just want to make that clear just in case it has any bearing on how this works. Mine resets to a click function but I'm sure it will work inside of an on change as well...

$("#select_id_wrap").find("select option").prop("selected", false);

Use the code below. See it working here http://jsfiddle.net/usmanhalalit/3HPz4/

 $(function(){
     $('#name').change(function(){
         $('#name2 option[value=""]').attr('selected','selected');
     });

     $('#name2').change(function(){
         $('#name option[value=""]').attr('selected','selected');
     });
 });

This can also be used

$('#name2').change(function(){
    $('#name').val('');//You can set the first value of first one if that is not empty
});


$('#name').change(function(){
    $('#name2').val('');
});

This is the most flexible/reusable way to reset all select boxes in your form.

      var $form = $('form') // Replace with your form selector
      $('select', $form).each(function() {
        $(this).val($(this).prop('defaultSelected'));
      });

Here's how to handle it with a random option element defined as the default value (in this case Text 2 is the default):

<select id="name2" >
   <option value="">select all</option>
   <option value="1">Text 1</option>
   <option value="2" selected="selected">Text 2</option>
   <option value="3">Text 3</option>
</select>
<script>
    $('#name2 option[selected]').prop('selected', true);
</script>

You can try this:

$( 'select' ).each( function () {
    if ( $( this ).children().length > 0 ) {
        $( $( this ).children()[0] ).attr( 'selected', 'selected' );
        $( this ).change();
    }
} );

I had a problem using the defaultSelected property in the answer by @Jens Roland in jQuery v1.9.1. A more generic way (with many dependent selects) would be to put a data-default attribute in your dependent selects and then iterate through them when reseting.

<select id="name0" >
    <option value="">reset</option>
    <option value="1">Text 1</option>
    <option value="2">Text 2</option>
    <option value="3">Text 3</option>
</select>

<select id="name1" class="name" data-default="1">
    <option value="">select all</option>
    <option value="1" selected="true">Text 1</option>
    <option value="2">Text 2</option>
    <option value="3">Text 3</option>
</select>

<select id="name2" class="name" data-default="2">
    <option value="">select all</option>
    <option value="1">Text 1</option>
    <option value="2" selected="true">Text 2</option>
    <option value="3">Text 3</option>
</select>

And the javascript...

$('#name0').change(function(){
    if($('#name0').val() == '') {
        $('select.name').each(function(index){
          $(this).val($(this).data('default'))  
        })
    } else {
      $('select.name').val($('#name0').val() );
    }
});

See http://jsfiddle.net/8hvqN/ for a working version of the above.


I created a new option in the select tag that has a value of empty string ("") and used:

$("form.query").find('select#topic').val("");

Use jquery for binding onchange event to select but you don't need to create another $(this) jquery object.

$('select[name=name2]').change(function(){
    if (this.value) {
        console.log('option value = ', this.value);
        console.log('option text  = ', this.options[this.selectedIndex].text);

        // Reset selected
        this.selectedIndex = this.defaultSelected;
    }
});

Use this code to reset all selection fields to the default option, where the attribute selected is defined.

<select id="name1" >
    <option value="1">Text 1</option>
    <option value="2" selected="selected" >Default Text 2</option>
    <option value="3">Text 3</option>
</select>
<select id="name2" >
    <option value="1">Text 1</option>
    <option value="2">Text 2</option>
    <option value="3" selected="selected" >Default Text 3</option>
</select>
<script>
    $('select').each( function() {
        $(this).val( $(this).find("option[selected]").val() );
    });
</script>

Here is the best solution im using. This will apply for over 1 slectbox

$("select").change(function(){
    var thisval = $(this).val();
    $("select").prop('selectedIndex',0);
    $(this).val(thisval);
})


Very simple:

$('#DropdownToRestId').find('option:selected').val('');

참고URL : https://stackoverflow.com/questions/7445492/how-to-set-the-first-option-on-a-select-box-using-jquery

반응형