Programming

라디오 버튼을 선택 해제하는 방법?

procodes 2020. 2. 16. 20:53
반응형

라디오 버튼을 선택 해제하는 방법?


jQuery를 사용하여 AJAX 양식을 제출 한 후 선택 취소하려는 라디오 버튼 그룹이 있습니다. 다음과 같은 기능이 있습니다.

function clearForm(){
  $('#frm input[type="text"]').each(function(){
      $(this).val("");  
  });
  $('#frm input[type="radio":checked]').each(function(){
      $(this).checked = false;  
  });
 }

이 기능을 사용하면 텍스트 상자에서 값을 지울 수 있지만 라디오 버튼의 값을 지울 수는 없습니다.

그건 그렇고, 나는 또한 시도 $(this).val("");했지만 작동하지 않았습니다.


어느 쪽이든 (일반 js)

this.checked = false;

또는 (jQuery)

$(this).prop('checked', false);
// Note that the pre-jQuery 1.6 idiom was
// $(this).attr('checked', false);

attr ()prop () 의 차이점 과 prop ()이 선호 되는 이유에 대한 설명 jQuery prop () 도움말 페이지참조하십시오 . prop ()는 2011 년 5 월 jQuery 1.6과 함께 도입되었습니다.


each기능이 필요하지 않습니다

$("input:radio").attr("checked", false);

또는

$("input:radio").removeAttr("checked");

텍스트 상자에도 동일하게 적용됩니다.

$('#frm input[type="text"]').val("");

하지만 당신은 이것을 향상시킬 수 있습니다

$('#frm input:text').val("");

시험

$(this).removeAttr('checked')

많은 브라우저가 'checked = anything'을 true로 해석하므로 이것은 확인 된 속성을 모두 제거합니다.

도움이 되었기를 바랍니다.


Igor의 코드를 기반으로 Laurynas의 플러그인을 약간 수정했습니다. 이는 대상 라디오 버튼과 관련된 가능한 레이블을 수용합니다.

(function ($) {
    $.fn.uncheckableRadio = function () {

        return this.each(function () {
            var radio = this;
                $('label[for="' + radio.id + '"]').add(radio).mousedown(function () {
                    $(radio).data('wasChecked', radio.checked);
                });

                $('label[for="' + radio.id + '"]').add(radio).click(function () {
                    if ($(radio).data('wasChecked'))
                        radio.checked = false;
                });
           });
    };
})(jQuery);

고마워 패트릭, 내 하루를 만들었 어 마우스 다운을 사용해야합니다. 그러나 코드를 개선하여 라디오 버튼 그룹을 처리 할 수 ​​있습니다.

//We need to bind click handler as well
//as FF sets button checked after mousedown, but before click
$('input:radio').bind('click mousedown', (function() {
    //Capture radio button status within its handler scope,
    //so we do not use any global vars and every radio button keeps its own status.
    //This required to uncheck them later.
    //We need to store status separately as browser updates checked status before click handler called,
    //so radio button will always be checked.
    var isChecked;

    return function(event) {
        //console.log(event.type + ": " + this.checked);

        if(event.type == 'click') {
            //console.log(isChecked);

            if(isChecked) {
                //Uncheck and update status
                isChecked = this.checked = false;
            } else {
                //Update status
                //Browser will check the button by itself
                isChecked = true;

                //Do something else if radio button selected
                /*
                if(this.value == 'somevalue') {
                    doSomething();
                } else {
                    doSomethingElse();
                }
                */
            }
    } else {
        //Get the right status before browser sets it
        //We need to use onmousedown event here, as it is the only cross-browser compatible event for radio buttons
        isChecked = this.checked;
    }
}})());

Igor의 코드를 플러그인으로 다시 작성하십시오.

사용하다:

$('input[type=radio]').uncheckableRadio();

플러그인:

(function( $ ){

    $.fn.uncheckableRadio = function() {

        return this.each(function() {
            $(this).mousedown(function() {
                $(this).data('wasChecked', this.checked);
            });

            $(this).click(function() {
                if ($(this).data('wasChecked'))
                    this.checked = false;
            });
        });

    };

})( jQuery );

라디오 및 라디오 그룹의 경우 :

$(document).ready(function() {
    $(document).find("input:checked[type='radio']").addClass('bounce');   
    $("input[type='radio']").click(function() {
        $(this).prop('checked', false);
        $(this).toggleClass('bounce');

        if( $(this).hasClass('bounce') ) {
            $(this).prop('checked', true);
            $(document).find("input:not(:checked)[type='radio']").removeClass('bounce');
        }
    });
});

이것을 시도하십시오, 이것은 속임수를 할 것입니다 :

        $(document).ready(function() {
           $("input[type='radio']").mousedown(function(e) {
                if ($(this).attr("checked") == true) {
                   setTimeout("$('input[id=" + $(this).attr('id') + "]').removeAttr('checked');", 200);}
                else {
                    return true
                }
            });
        });

시험

$(this).attr("checked" , false );

확인란 만 사용하여 라디오 버튼 동작을 시뮬레이션 할 수도 있습니다.

<input type="checkbox" class="fakeRadio" checked />
<input type="checkbox" class="fakeRadio" />
<input type="checkbox" class="fakeRadio" />

그런 다음이 간단한 코드를 사용하여 작업 할 수 있습니다.

$(".fakeRadio").click(function(){
    $(".fakeRadio").prop( "checked", false );
    $(this).prop( "checked", true );
});

잘 작동하고 각 버튼의 동작을 더 잘 제어 할 수 있습니다.

http://jsfiddle.net/almircampos/n1zvrs0c/ 에서 직접 시도해 볼 수 있습니다.

이 포크를 사용하면 주석에서 요청한대로 모두 선택을 취소 할 수 있습니다. http://jsfiddle.net/5ry8n4f4/


jQuery에 다음 코드를 넣으십시오.

jQuery("input:radio").removeAttr("checked");

그리고 자바 스크립트의 경우 :

$("input:radio").removeAttr("checked");

foreach 루프, .each () fubction 또는 어떤 것도 넣을 필요가 없습니다.


이것을 사용하십시오

$("input[name='nameOfYourRadioButton']").attr("checked", false);

$('#frm input[type="radio":checked]').each(function(){
   $(this).checked = false;  
  });

이것은 거의 좋지만 [0]을 놓쳤습니다.

수정->> $(this)[0].checked = false;


이 JQuery를 사용하여 선택 취소 라디오 버튼을 사용할 수 있습니다

$('input:radio[name="IntroducerType"]').removeAttr('checked');
                $('input:radio[name="IntroducerType"]').prop('checked', false);

function setRadio(obj) 
{
    if($("input[name='r_"+obj.value+"']").val() == 0 ){
      obj.checked = true
     $("input[name='r_"+obj.value+"']").val(1);
    }else{
      obj.checked = false;
      $("input[name='r_"+obj.value+"']").val(0);
    }

}

<input type="radio" id="planoT" name="planoT[{ID_PLANO}]" value="{ID_PLANO}" onclick="setRadio(this)" > <input type="hidden" id="r_{ID_PLANO}" name="r_{ID_PLANO}" value="0" >

:디


$('input[id^="rad"]').dblclick(function(){
    var nombre = $(this).attr('id');
    var checked =  $(this).is(":checked") ;
    if(checked){
        $("input[id="+nombre+"]:radio").prop( "checked", false );
    }
});

확인 된 라디오를 두 번 클릭 할 때마다 확인 된 변경이 false로 변경됩니다.

id=radxxxxxxxx이 ID 선택기를 사용하기 때문에 라디오가 시작됩니다 .


function clearForm(){
  $('#frm input[type="text"]').each(function(){
      $(this).val("");  
  });
  $('#frm input[type="radio":checked]').each(function(){
      $(this).attr('checked', false);  
  });
 }

올바른 선택은 다음과 같습니다 #frm input[type="radio"]:checked하지#frm input[type="radio":checked]

참고 URL : https://stackoverflow.com/questions/2117538/how-to-uncheck-a-radio-button



반응형