복붙노트

[JQUERY] jQuery를 라디오에 따라 사용 안 함 옵션을 선택합니다 (모든 브라우저에 대한 필요 지원) 선택

JQUERY

jQuery를 라디오에 따라 사용 안 함 옵션을 선택합니다 (모든 브라우저에 대한 필요 지원) 선택

해결법


  1. 1.당신이 원하는 기능을 달성하기위한 적절한 방법은 옵션을 제거하는 것입니다. 하드 방법을 발견으로, 개별 옵션을 사용하지 않도록 설정하면 브라우저에서 특히 잘 지원되지 않습니다. 난 그냥 일어나서 쉽게는 라디오의 선택 ID의 속성에 따라 선택 필터에 난 작은 플러그인을 채찍질 그래서 뭔가 프로그래밍 같은 느낌. 솔루션의 나머지는 작업이 완료 얻을 것이다 있지만 앱을 통해이 일을 계획하는 경우에,이 도움이 될 것입니다. 그렇지 않다면, 나는 다른 사람에 대한 추측이시 실수를 한단다 그. 여기에 당신이 어딘가에 멀리 숨길 수있는 플러그인 코드는 다음과 같습니다

    당신이 원하는 기능을 달성하기위한 적절한 방법은 옵션을 제거하는 것입니다. 하드 방법을 발견으로, 개별 옵션을 사용하지 않도록 설정하면 브라우저에서 특히 잘 지원되지 않습니다. 난 그냥 일어나서 쉽게는 라디오의 선택 ID의 속성에 따라 선택 필터에 난 작은 플러그인을 채찍질 그래서 뭔가 프로그래밍 같은 느낌. 솔루션의 나머지는 작업이 완료 얻을 것이다 있지만 앱을 통해이 일을 계획하는 경우에,이 도움이 될 것입니다. 그렇지 않다면, 나는 다른 사람에 대한 추측이시 실수를 한단다 그. 여기에 당신이 어딘가에 멀리 숨길 수있는 플러그인 코드는 다음과 같습니다

    jQuery.fn.filterOn = function(radio, values) {
        return this.each(function() {
            var select = this;
            var options = [];
            $(select).find('option').each(function() {
                options.push({value: $(this).val(), text: $(this).text()});
            });
            $(select).data('options', options);
            $(radio).click(function() {
                var options = $(select).empty().data('options');
                var haystack = values[$(this).attr('id')];
                $.each(options, function(i) {
                    var option = options[i];
                    if($.inArray(option.value, haystack) !== -1) {
                        $(select).append(
                        $('<option>').text(option.text).val(option.value)
                        );
                    }
                });
            });            
        });
    };
    

    그리고 여기에 그것을 사용하는 방법입니다 :

    $(function() {
        $('#theOptions').filterOn('input:radio[name=abc123]', {
            'abc': ['a','b','c'],
            '123': ['1','2','3']        
        });
    });
    

    첫 번째 인자는 무선 그룹 키가 무선 ID가 일치한다 번째 사전하는 선택기이며, 값 옵션 값이 유지되어야 선택한 항목의 배열이다. 이 더 추상적으로 할 수있는 일들이 많이있다, 당신이 관심이 있다면 알려 주시면 확실히 그렇게 할 수 있습니다.

    여기에 행동에 그것의 데모입니다.

    편집 : 또한, jQuery를 문서에 따라 추가 깜빡 :


  2. 2.당신이 뭔가를 원하는 - 예제 코드를 여기에

    당신이 뭔가를 원하는 - 예제 코드를 여기에

    $(function() {
    
    $("input:radio[@name='abc123']").click(function() {
       if($(this).attr('id') == 'abc') {
    
          // Disable 123 and Enable abc
          $("#theOptions option[value='1']").attr("disabled","disabled");
          $("#theOptions option[value='2']").attr("disabled","disabled");
          $("#theOptions option[value='3']").attr("disabled","disabled");
          $("#theOptions option[value='a']").attr("selected","selected");
          $("#theOptions option[value='a']").attr("disabled","");
          $("#theOptions option[value='b']").attr("disabled","");
          $("#theOptions option[value='c']").attr("disabled","");
    
       } else {
          // Disable abc's and Enable 123
          $("#theOptions option[value='a']").attr("disabled","disabled");
          $("#theOptions option[value='b']").attr("disabled","disabled");
          $("#theOptions option[value='c']").attr("disabled","disabled");
          $("#theOptions option[value='1']").attr("selected","selected");          
          $("#theOptions option[value='1']").attr("disabled","");   
          $("#theOptions option[value='2']").attr("disabled","");
          $("#theOptions option[value='3']").attr("disabled","");
    
       }    
    });
    
    });
    

    편집하다:

    옵션 값에 따라 필터 옵션에 정규 표현식을 사용하여 코드의 버전을 개선. 여기 예를 들어 작업. 당신은 URL에 / 편집을 추가하여 예를 편집 할 수 있습니다

    $(function() {
    
        $("input:radio[@name='abc123']").click(function() {
    
            // get the id of the selected radio
            var radio = $(this).attr('id'); 
    
            // set variables based on value of radio
            var regexDisabled = radio == 'abc' ?  /[1-3]/ : /[a-c]/;      
            var regexEnabled = radio == 'abc' ? /[a-c]/ : /[1-3]/;
            var selection = radio == 'abc' ? 'a' : 1;
    
            // select all option elements who are children of id #theOptions
            $("#theOptions option")
                // filter the option elements to only those we want to disable
                .filter( function() { return this.value.match(regexDisabled);})
                // disable them
                .attr("disabled","disabled")
                // return to the previous wrapped set i.e. all option elements
                .end()
                // and filter to those option elements we want to enable
                .filter( function() { return this.value.match(regexEnabled);})
                // enable them
                .attr("disabled","");
           // change the selected option element in the dropdown
           $("#theOptions option[value='" + selection + "']").attr("selected","selected");
    
        });
    
    });
    

    편집 2 :

    장애인 속성 브라우저에서 안정적으로 작동하는 것처럼하지 않기 때문에, 나는 당신의 유일한 옵션은 옵션 요소 라디오 버튼을 선택하면 필요하지를 제거하는 것입니다 생각합니다. 작업 예 여기

      $(function() {
    
            $("input:radio[@name='abc123']").click(function() {
    
                // store the option elements in an array
                var options = [];
                options[0] = '<option value="1">1</option>';
                options[1] = '<option value="2">2</option>';
                options[2] = '<option value="3">3</option>';
                options[3] = '<option value="a">a</option>';
                options[4] = '<option value="b">b</option>';
                options[5] = '<option value="c">c</option>';
    
    
                var radio = $(this).attr('id');   
                var regexEnabled = radio == 'abc' ? /[a-c]/ : /[1-3]/;
    
                // set the option elements in #theOptions to those that match the regular expression
                $("#theOptions").html(
                $(options.join(''))
                    // filter the option elements to only those we want to include in the dropdown
                    .filter( function() { return this.value.match(regexEnabled);})
                );
    
    
            });
    
        });
    

    또는

      $(function() {
    
            // get the child elements of the dropdown when the DOM has loaded
            var options = $("#theOptions").children('option');
    
            $("input:radio[@name='abc123']").click(function() {         
    
                var radio = $(this).attr('id');   
                var regexEnabled = radio == 'abc' ? /[a-c]/ : /[1-3]/;
    
                // set the option elements in #theOptions to those that match the regular expression
                $("#theOptions").html(
                $(options)
                    // filter the option elements to only those we want to include in the dropdown
                    .filter( function() { return this.value.match(regexEnabled);})
                );
    
            }); 
        });
    

  3. 3.첫 번째 문제는 함께

    첫 번째 문제는 함께

    $(this).val()
    

    로 교체

    $(this).attr('id') == 'abc'
    

    다음이 작동하지 않습니다

    $("'theOptions'..")
    

    사용하다

    $("#theOptions option[value='1']").attr('disabled','disabled') //to disable
    $("#theOptions option[value='a']").attr('disabled','') //to ENABLE
    

  4. 4.당신은 어떤 브라우저를 사용하고 있습니까? 나는 그것을 전에 사용한 적이 있지만, IE8 이전 IE에서 지원되지 않는 것 같다. 자세한 내용은이 링크를 참조하십시오 :

    당신은 어떤 브라우저를 사용하고 있습니까? 나는 그것을 전에 사용한 적이 있지만, IE8 이전 IE에서 지원되지 않는 것 같다. 자세한 내용은이 링크를 참조하십시오 :

    http://www.w3schools.com/TAGS/att_option_disabled.asp


  5. 5.당신의 선택은 잘못된 것입니다. 대신에

    당신의 선택은 잘못된 것입니다. 대신에

    $("'theOptions' option[value='1']")
    

    당신은 사용해야합니다

    $("#theOptions > option[value='1']")
    

    또한 jQuery를 선택기 설명서를 참조하십시오. 그리고 aman.tur에 의해 제안에서보세요.


  6. 6.

    $(":radio[name=abc123]").click(function() {
       var $options = $("#theOptions")
       var toggle = ($(this).val() == 'abc') ? true : false;
    
       $("[value=1],[value=2],[value=3]", $options).attr("disabled", toggle);
       $("[value=a],[value=b],[value=c]", $options).attr("disabled", !toggle);
    });
    

  7. 7.당신은 몇 가지 옵션을 사용하지 않을 경우에 비해에게 아래의 코드는 작동합니다

    당신은 몇 가지 옵션을 사용하지 않을 경우에 비해에게 아래의 코드는 작동합니다

    $("input:radio[name='abc123']").click(function() {
       var value = $(this).val();
    
       $("option[value='1'], option[value='2'], option[value='3']", "#theOptions").each(function(){
          this.disabled = value == 'abc';
       });
       $("option[value='a'], option[value='b'], option[value='c']", "#theOptions").each(function(){
          this.disabled = value == '123';
       })
    });
    

    및 무선 버튼

    ABC: <input type="radio" name="abc123" value="abc" id="abc"/>
    123: <input type="radio" name="abc123" value="123" id="123"/>
    

    이 코드를 사용하여보다 선택 목록에서 옵션을 제거하려면

    $(function(){
       var options = null;
       $("input:radio[name='abc123']").click(function() {
          var value = $(this).val();
          if(options != null)options.appendTo('#theOptions');
          if(value == 'abc' )
             options = $("option[value='1'], option[value='2'], option[value='3']", "#theOptions").remove();
          else if(value == '123')
             options = $("option[value='a'], option[value='b'], option[value='c']", "#theOptions").remove();
       });
    });
    

    BTW. 내 코드는 jQuery를 현재의 안정적인 릴리스 (1.3.2)를 사용합니다. 당신이 이전 버전을 사용하는 경우, 이전 구문에 속성 선택기를 변경해야합니다.

    옵션 [VALUE = '1'] 항목 내지 [@ 값 = '1']


  8. 8.단지 ( " '눌러 옵션'옵션 [VALUE = '1']")에 셀렉터를 $ 해결 $ ( "#을 눌러 옵션 옵션 [값 = '1']") 모든 것이 잘 작동합니다

    단지 ( " '눌러 옵션'옵션 [VALUE = '1']")에 셀렉터를 $ 해결 $ ( "#을 눌러 옵션 옵션 [값 = '1']") 모든 것이 잘 작동합니다

  9. from https://stackoverflow.com/questions/877328/jquery-disable-select-options-based-on-radio-selected-need-support-for-all-brow by cc-by-sa and MIT license