UFO ET IT

jQuery로 jquery가 선택한 선택 옵션을 어떻게 재설정합니까?

ufoet 2020. 11. 12. 20:40
반응형

jQuery로 jquery가 선택한 선택 옵션을 어떻게 재설정합니까?


나는 많은 것을 시도했지만 아무것도 작동하지 않는 것 같습니다.

jQuery 및 Chosen 플러그인을 사용하고 있습니다.

내가 시도한 방법 :

var select = jQuery('#autoship_option');

select.val(jQuery('options:first', select).val());

jQuery('#autoship_option').val('');

jQuery('#autoship_option').text('');

jQuery('#autoship_option').empty('');

jQuery("#autoship_option option[value='']").attr('selected', true);

일단 선택되면 항상 Active Autoship 옵션이 표시됩니다. 선택을 취소 할 수없는 것 같습니다.

선택 상자는 다음과 같습니다.

<select id="autoship_option" data-placeholder="Choose Option..." 
style="width: 175px;" class="chzn-select">
    <option value=""></option>
    <option value="active">Active Autoship</option>
</select>

Chosen에 익숙하고 하나의 옵션으로 선택 상자를 지울 수있는 사람이 있습니까? (앞으로 더 많은 옵션이있을 것입니다.


select요소의 값을 빈 문자열로 설정하는 것이 올바른 방법입니다. 그러나 이는 루트 select요소 만 업데이트합니다 . 사용자 정의 chosen요소는 루트 select가 업데이트되었는지 알지 못합니다 .

통지하기 위해 chosen이 것을 select수정 된 경우에는 트리거가 chosen:updated:

$('#autoship_option').val('').trigger('chosen:updated');

또는 첫 번째 옵션이 빈 문자열인지 확실하지 않은 경우 다음을 사용하십시오.

$('#autoship_option')
    .find('option:first-child').prop('selected', true)
    .end().trigger('chosen:updated');

여기에서 문서를 읽으 십시오 ( 동적으로 선택한 업데이트 섹션 찾기 ).


PS 이전 버전의 Chosen은 약간 다른 이벤트를 사용합니다.

$('#autoship_option').val('').trigger('liszt:updated');

첫 번째 옵션이 충분해야합니다 : http://jsfiddle.net/sFCg3/

jQuery('#autoship_option').val('');

그러나 jsfiddle과 같은 click버튼 ready이나 문서와 같은 이벤트에서 이것을 실행하고 있는지 확인해야합니다 .

또한 옵션 태그에 항상 값 속성이 있는지 확인하십시오. 그렇지 않은 경우 일부 브라우저는 항상 val().

편집 :
이제 Chosen 플러그인의 사용을 명확히 했으므로 다음을 호출해야합니다.

$("#autoship_option").trigger("liszt:updated");

인터페이스를 업데이트하기 위해 값을 변경 한 후.

http://harvesthq.github.com/chosen/


Latest Chosen JS로 업데이트 된 선택 상자를 다시로드하려면 이것을 시도하십시오.

$("#form_field").trigger("chosen:updated");

http://harvesthq.github.io/chosen/

Ajax를 사용하여 새로로드 된 선택 상자로 선택한 드롭 다운을 업데이트합니다.


이 시도:

$("#autoship_option option[selected]").removeAttr("selected");

나는 이것을 사용한다 :

$('idSelect').val([]);

IE, Safari 및 Firefox에서 테스트 됨


이것은 찾기보다 더 효과적입니다.

$('select').children('option').first().prop('selected', true)
$('select').trigger("chosen:updated");

var config = {
      '.chosen-select'           : {},
      '.chosen-select-deselect'  : {allow_single_deselect:true},
      '.chosen-select-no-single' : {disable_search_threshold:10},
      '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
      '.chosen-select-width'     : {width:"95%"}
    }
    for (var selector in config) {
      $(selector).chosen(config[selector]);
    }

위의 구성을 사용하고 class='chosen-select-deselect'수동으로 선택 취소하고 값을 비워 두십시오.

또는 모든 콤보에서 옵션을 선택 취소하려면 아래와 같이 구성을 적용하십시오.

var config = {
  '.chosen-select'           : {allow_single_deselect:true},//Remove if you do not need X button in combo
  '.chosen-select-deselect'  : {allow_single_deselect:true},
  '.chosen-select-no-single' : {disable_search_threshold:10},
  '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
  '.chosen-select-width'     : {width:"95%"}
}
for (var selector in config) {
  $(selector).chosen(config[selector]);
}

$('#autoship_option').val('').trigger('liszt:updated');

기본 옵션 값을로 설정합니다 ''.

https://raw.github.com/harvesthq/chosen/master/chosen/chosen.jquery.min.js 링크에서 사용할 수있는 선택된 업데이트 된 jQuery와 함께 사용해야 합니다.

나는 마지막에 찾아 일 하루 동안 jquery.min다른chosen.jquery.min


jQuery("#autoship_option option:first").attr('selected', true);

I am not sure if this applies to the older version of chosen,but now in the current version(v1.4.1) they have a option $('#autoship_option').chosen({ allow_single_deselect:true }); This will add a 'x' icon next to the name selected.Use the 'x' to clear the 'select' feild.

PS:make sure you have 'chosen-sprite.png' in the right place as per the chosen.css so that the icons are visible.


In Chrome version 49

you need always this code

$("select option:first").prop('selected', true)


i think you have to assign a new value to the select, so if you want to clear your selection you probably want to assign it to the one that has value = "". I think that you will be able to get it by assigning the value to empty string so .val('')


HTML:

<select id="autoship_option" data-placeholder="Choose Option..." 
        style="width: 175px;" class="chzn-select">
    <option value=""></option>
    <option value="active">Active Autoship</option>
</select>
<button id="rs">Click to reset</button>

JS:

$('#rs').on('click', function(){
    $('autoship_option').find('option:selected').removeAttr('selected');
});

Fiddle: http://jsfiddle.net/Z8nE8/


You can try this to reset (empty) drop down

 $("#autoship_option").click(function(){
            $('#autoship_option').empty(); //remove all child nodes
            var newOption = $('<option value=""></option>');
            $('#autoship_option').append(newOption);
            $('#autoship_option').trigger("chosen:updated");
        });

The new Chosen libraries don't use the liszt. I used the following:

document.getElementById('autoship_option').selectedIndex = 0;
$("#autoship_option").trigger("chosen:updated");

If you need to have first option selected by no matter of its value (sometimes first option value is not empty) use this:

$('#autoship_option').val($('#autoship_option option:first-child').val()).trigger("liszt:updated");

It will get value of first option and set it as selected then trigger update on Chosen. So it work like reset to first option on list.


Exactly i had the same requirement. But resetting the drop down list by setting simply empty string with jquery won't work. You should also trigger update.

Html:
<select class='chosen-control'>
<option>1<option>
<option>2<option>
<option>3<option>
</select>

Jquery:
$('.chosen-control').val('').trigger('liszt:updated');

sometimes based on the version of chosen control you are using, you may need to use below syntax.

$('.chosen-control').val('').trigger("chosen:updated");

Reference: How to reset Jquery chosen select option


jQuery('.chosen-processed').find('.search-choice-close').click();

Simple add trigger change like this:

$('#selectId').val('').trigger('change');

If you are using chosen, a jquery plugin, then to refresh or clear the content of the dropdown use:

$('#dropdown_id').empty().append($('< option>'))

dropdown_id.chosen().trigger("chosen:updated")

chosen:updated event will re-build itself based on the updated content.


from above solutions, Nothing worked for me. This worked:

$('#client_filter').html(' '); //this worked

Why is that? :)

$.ajax({ 
        type: 'POST', 
        url: xyz_ajax,
        dataType: "json",
        data : { csrfmiddlewaretoken: csrftoken,
                instancess : selected_instances }, 
        success: function(response) { 
            //clear the client DD       
            $('#client_filter').val('').trigger('change') ; //not working
            $('#client_filter').val('').trigger('chosen:updated') ; //not working
            $('#client_filter').val('').trigger('liszt:updated') ; //not working
             $('#client_filter').html(' '); //this worked
             jQuery.each(response, function(index, item) {
                  $('#client_filter').append('<option value="'+item.id+'">' + item.text + '</option>');
                });                 
           $('#client_filter').trigger("chosen:updated");
        }
      });
     } 

참고URL : https://stackoverflow.com/questions/11365212/how-do-i-reset-a-jquery-chosen-select-option-with-jquery

반응형