UFO ET IT

jQuery를 사용하여 IE에서 선택 옵션 숨기기

ufoet 2021. 1. 11. 21:11
반응형

jQuery를 사용하여 IE에서 선택 옵션 숨기기


현재 다음 코드를 사용하여 선택 옵션을 숨기거나 표시하기 위해 jQuery를 사용하고 있습니다.

$("#custcol7 option[value=" + sizeValue + "]").hide();

이것은 Firefox에서 잘 작동하지만 다른 브라우저에서는 좋지 않습니다. Chrome, Opera 및 IE에서 선택 옵션을 숨기는 방법은 무엇입니까?


나는 방금 이것을 발견하고 전체 선택을 반복해서 복제하는 대신 span요소 로 숨겨야하는 옵션을 교체 하고 스팬을 숨겼습니다 (브라우저가 어쨌든 시각적으로 표시하지 않았지만 제 생각에는)-변경해야 할 수도 있습니다 복잡한 논리의 범위를 반복하는 코드 (복잡한 경우).

범위는에 대한 참조를 저장하고 option표시해야 할 때 자체적으로 대체합니다.

이 코드는 분명히 리팩토링되고 예쁘게 될 수 있습니다.

http://fiddle.jshell.net/FAkEK/12/show/

편집 # 2 (이 대신 사용) : 이 모든 복제 / 참조 / 교체 쓰레기를 수행하는 대신 옵션을 스팬으로 감싸고 스팬을 숨기고 쇼에서 스팬을 다시 옵션으로 교체하십시오. .

http://fiddle.jshell.net/FAkEK/25/show/


나는 meder 가 유효한 대답을 제공 했다고 생각 하며 여기에서 나를 위해 작동하는 것을 반영하기 위해 약간 변경되었습니다.

$.fn.optVisible = function( show ) {
    if( show ) {
        this.filter( "span > option" ).unwrap();
    } else {
        this.filter( ":not(span > option)" ).wrap( "<span>" ).parent().hide();
    }
    return this;
}

(긴 라이브 BrowserStack)으로 테스트 :

  • Windows XP : IE 6.0, Firefox 3.0, Safari 4.0, Opera 10.0, Chrome 14.0
  • Windows 8 : IE 10.0 Metro
  • iOS 3.2 (iPad), iOS 6.0 (iPhone 5)
  • Android 1.6 (Sony Xperia X10)

jsfiddle


그렇지 않습니다. IE에서는 지원되지 않습니다 (아마도 Chrome이나 Opera에서도 지원되지 않음). 옵션을 모두 제거하고 진정으로 보이지 않게하려면 나중에 다시 추가해야합니다. 그러나 대부분의 경우 간단한 방법으로도 disabled="disabled"충분하며 옵션 제거 및 추가를 처리하는 것보다 훨씬 간단합니다.


detach ()를 시도하십시오. 필요한 경우 append () 또는 insertAfter ()를 사용하여 나중에 다시 연결할 수 있습니다.


옵션을 제거하려면 다음을 사용하십시오.

var opt=$("option").detach();

옵션을 표시하려면 다음을 사용하십시오.

opt.appendTo( "select" );

그냥 삭제하고 JavaScript의 var에 저장하십시오. 나중에 필요할 때 새 개체를 만들 수 있습니다.

그렇지 않으면 disabled위에서 언급 한 속성을 시도하십시오 .


/**
* Change visibility of select list option elements
* @param  {boolean}   stateVal      show hidden options if true; hide it otherwise. If not setted then toggle visibility, based on it's current state
*/
$.fn.toggleOptionVisibility = function (stateVal) {
    var isBool = typeof stateVal === "boolean";
    return this.each(function () {
         var $this = $(this);
         if (isBool) {
             if (stateVal) $this.filter("span > option").unwrap();
             else $this.filter(":not(span > option)").wrap("<span>").parent().hide();
         }
         else {
             $this.filter("span > option").toggleOptionVisibility(true);
             $this.filter(":not(span > option)").toggleOptionVisibility(false);
        }
    });
};

당신이 한 방식은 크롬에서 작동해야하지만 nvm. 여기 또 다른 방법이 있습니다.

select = $('#custcol7');
select.find('option[value=["'+sizeValue +'"]').remove();

다시 표시하려면 :

select.append('<option value="'+sizeValue+'"></option>');

모든 브라우저와 정말 간단한 코드에서 완벽하게 작동합니다. 문제는 여러 옵션을 숨기고 싶다면 .. 타이핑하는 것이 더 많지만 동적으로 변경되지 않으면 변수에 넣음으로써 해결할 수 있습니다.

var options = '<option value="'+sizeValue1+'"></option><option value="'+sizeValue2+'"></option><option value="'+sizeValue3+'"></option>';

select.append(options);

이 방법으로 여러 곳에서 제거 / 추가해야하는 경우 옵션을 한 번만 입력했습니다. 또 다른 흥미로운 옵션을 제공했으면합니다. 친애하는.


.load 메서드도 있습니다.

s_parent.change(function(){
   s_child.load('./fetch_options.php",{'v',s_parent.val()});
}

'fetch_options.php'스크립트는 사용하는 데이터 소스와 전달되는 상위 값을 기반으로 옵션 태그를 인쇄합니다.


AuthorProxy에서 제공하는 솔루션을 사용하면 IE에서는 잘 작동하지만 firefox의 드롭 다운에서 .val ()을 시도하면 의미가없는 펑키 한 값이 표시됩니다. 브라우저 특정 기능을 포함하도록 옵션을 수정하고, firefox에서 작동하는 숨기기 / 표시를했습니다.

$.fn.toggleOptionVisibility = function (stateVal) {
    var isBool = typeof stateVal === "boolean";
    return this.each(function () {
        var $this = $(this);
        if (navigator.userAgent.indexOf('MSIE') > -1 || navigator.userAgent.indexOf('Trident') > -1) {
            if (isBool) {
                if (stateVal) $this.filter("span > option").unwrap();
                else $this.filter(":not(span > option)").wrap("<span>").parent().hide();
            }
            else {
                $this.filter("span > option").toggleOptionVisibility(true);
                $this.filter(":not(span > option)").toggleOptionVisibility(false);
            }   
        }
        else {              
            if (isBool) {
                $this.show();
            }
            else {
                $this.hide();
            }
        }
    });
};

My take is bit different to other answers.

The aim is not to hide the options but just make them disable(to keep the UI consistent).

My Scenario :

I have multiple selects in a form and when an user selects an option in one of the selects the other selects should disable this option and vice versa. User is restricted from selecting the same option which is already selected. We normally disable the option but for IE 7 which does not support it. User also gets an option to add new selects.

Solution :

On load :

If the browser is IE7 then while populating the the selects and disabling the already selected options on other selects I am adding a custom attribute to the option("data-ie7-disabled") and also changing the color of the disabled options to '#cccccc'(which is the standard color for disabled options). This makes the UI look same across browsers.

On Change :

I save the previous option in a local variable(this is saved on focus).

When a user tries to change an option

  1. User selects a complete new option which is not selected in any other dropdown. Then I loop through other selects and change the color and add custom attribute to this selected option on other selects.

  2. When user selects an option that is already selected(The option which has grayed out color). I check if the option has this custom attribute on it first. If it has then > I simply revert the option to the previous one with an error message saying "This option is already selected or BLAH BLAH".

  3. When user changes his existing option to a brand new option which is not selected in any other dropdown's. I again loop through all the other select options and remove the color on it and also the custom attribute.

Hope this helps.


You can use through combinations of var $opt=$('select>option').clone() and $('select option[value="'+val+'"').remove(). There is another example: try this. https://jsfiddle.net/sherali/jkw8fxzf/12/

var $secondOption= $('#second-choice>option').clone();

$("#first-choice").change(function() {
    var userSelected = $(this).val();

    $('#second-choice').html($secondOption);
    $('#second-choice option[value="'+userSelected+'"').remove()
});

You will need to remove it and then add it again for Internet Explorer.

To remove:

$("#custcol7 option[value=" + sizeValue + "]").remove();

To add:

$("#custcol7").append( "<option value='sizeValue'>sizeValue</option>" );

Note that you need to have sizeValue also in the option text, to actually see something.


You can also replace the html within the select.

Html:

<input id="Button1" type="button" value="hide option" />

<select id="foo">
<option >stuff</option>
<option >stuff2</option>
</select>

Jquery:

    $("#Button1").change(function () {
       $('#foo').html('<option >stuff</option>');
    });

Not exactly what you want, but perhaps it helps. For smaller dropdowns, it is definitely easier.


In IE 11(Edge), the following code is working.

 $("#id option[value='1']").remove();

and to ad back,

$('<option>').val('1').text('myText').appendTo('#id');

meder's solution is what I went with for this, but with a small tweak to prevent it from wrapping an option in a span that was already in a span:

$.fn.hideOption = function() {
    this.each(function() {
        if (!$(this).parent().is('span')) {
            $(this).wrap('<span>').hide();
        }
    });
};
$.fn.showOption = function() {
    this.each(function() {
        var opt = $(this).find('option').show();
        $(this).replaceWith(opt);
    });
};

You can use this:

$("#custcol7 option[value=" + sizeValue + "]").css({display:'none'});

It works fine on all browsers except Safari and Opera. I'm searching for another best solution :)

ReferenceURL : https://stackoverflow.com/questions/2031740/hide-select-option-in-ie-using-jquery

반응형