Programing

라디오 버튼이 JQuery로 선택되어 있는지 확인하십시오.

lottogame 2020. 10. 4. 10:15
반응형

라디오 버튼이 JQuery로 선택되어 있는지 확인하십시오.


라디오 버튼을 잘 체크하도록 설정할 수 있지만 원하는 것은 특정 라디오 버튼이 체크 될 때 활성화되는 일종의 '리스너'를 설정하는 것입니다.

예를 들어 다음 코드를 살펴보십시오.

$("#element").click(function()
{ 
    $('#radio_button').attr("checked", "checked");
});

확인 된 속성을 추가하고 모든 것이 잘되지만 경고를 추가하는 방법은 무엇입니까? 예를 들어, 클릭 기능의 도움없이 라디오 버튼을 선택하면 팝업이 표시됩니까?


$('#element').click(function() {
   if($('#radio_button').is(':checked')) { alert("it's checked"); }
});

동일한 이름 속성을 공유하는 라디오 버튼 그룹이 있고 제출시 또는 이벤트시 이러한 라디오 버튼 중 하나가 선택되었는지 확인하려는 경우 다음 코드를 사용하여 간단히 수행 할 수 있습니다.

$(document).ready(function(){
  $('#submit_button').click(function() {
    if (!$("input[name='name']:checked").val()) {
       alert('Nothing is checked!');
        return false;
    }
    else {
      alert('One of the radio buttons is checked!');
    }
  });
});

출처

jQuery API 참조


Parag의 솔루션이 나에게 오류를 던 졌기 때문에 다음은 내 솔루션입니다 (David Hedlund와 Parag의 결합).

if (!$("input[name='name']").is(':checked')) {
   alert('Nothing is checked!');
}
else {
   alert('One of the radio buttons is checked!');
}

이것은 나를 위해 잘 작동했습니다!


변경 이벤트가 IE에서 작동하지 않으므로 확인란의 클릭 이벤트를 바인딩해야합니다.

$('#radio_button').click(function(){
    // if ($(this).is(':checked')) alert('is checked'); 
    alert('check-checky-check was changed');
});

이제 프로그래밍 방식으로 상태를 변경할 때이 이벤트도 트리거해야합니다.

$('#radio_button').attr("checked", "checked");
$('#radio_button').click();

// 수업 확인

if($("input:radio[class='className']").is(":checked")) {
     //write your code         
}

// 이름 확인

if($("input:radio[name='Name']").is(":checked")) {
         //write your code         
}

// 데이터 확인

if($("input:radio[data-name='value']").is(":checked")) {
         //write your code         
}

또 다른 방법은 (jQuery> = 1.6) 사용하는 것입니다 .prop

$("input[type=radio]").click(function () {
    if($(this).prop("checked")) { alert("checked!"); }
});

솔루션은 간단 할 것입니다. 특정 라디오 버튼이 선택 될 때 '리스너'가 필요하기 때문입니다. 해 :-

if($('#yourRadioButtonId').is(':checked')){ 
// Do your listener's stuff here. 
}

클릭 기능을 원하지 않는 경우 Jquery 변경 기능을 사용하십시오.

$('#radio_button :checked').live('change',function(){
alert('Something is checked.');
});

이것이 당신이 찾고있는 대답이어야합니다. 1.9.1 이상의 Jquery 버전을 사용하는 경우 라이브 기능이 더 이상 사용되지 않으므로 on을 사용하십시오.


... 고마워요 ... 내가 필요한 것은 세트의 각 라디오 버튼이 다른 ID를 갖는 체크 라디오 버튼의 '값'뿐이었습니다 ...

 var user_cat = $("input[name='user_cat']:checked").val();

나를 위해 작동합니다 ...


모든 유형의 라디오 버튼 및 브라우저 작업

if($('#radio_button_id')[0].checked) {
   alert("radiobutton checked")
}
else{
   alert("not checked");
}

Working Jsfiddle Here


dynamic generated Radio Button Check radio get value

$("input:radio[name=radiobuttonname:checked").val();

On change dynamic Radio button

$('input[name^="radioname"]').change(function () {if (this.value == 2) { }else{}});

$('.radio-button-class-name').is('checked') didn't work for me, but the next code worked well:

    if(typeof $('.radio-button-class-name:checked').val() !== 'undefined'){
     // radio button is checked
    }

try this

    if($('input[name="radiobutton"]:checked').length == 0) {
        alert("Radio buttons are not checked");
    }

Try this:

alert($('#radiobutton')[0].checked)

jQuery is still popular, but if you want to have no dependencies, see below. Short & clear function to find out if radio button is checked on ES-2015:

function getValueFromRadioButton( name ){
  return [...document.getElementsByName(name)]
         .reduce( (rez, btn) => (btn.checked ? btn.value : rez), null)
}

console.log( getValueFromRadioButton('payment') );
<div>  
  <input type="radio" name="payment" value="offline">
  <input type="radio" name="payment" value="online">
  <input type="radio" name="payment" value="part" checked>
  <input type="radio" name="payment" value="free">
</div>


$("#radio_1").prop("checked", true);

For versions of jQuery prior to 1.6, use:

$("#radio_1").attr('checked', 'checked');

참고URL : https://stackoverflow.com/questions/2272507/find-out-whether-radio-button-is-checked-with-jquery

반응형