program tip

JQuery를 사용하여 그룹의 라디오 버튼이 확인되지 않았는지 확인

radiobox 2020. 8. 21. 07:30
반응형

JQuery를 사용하여 그룹의 라디오 버튼이 확인되지 않았는지 확인


나는 문제가 있습니다. 라디오 버튼 그룹에 라디오 버튼이 선택되어 있지 않은지 JQuery로 확인하여 사용자가 옵션을 확인하는 것을 잊었을 때 자바 스크립트 오류를 ​​줄 수 있습니다.

값을 얻기 위해 다음 코드를 사용하고 있습니다.

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

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

나는 사용하고있다

$("input:radio[name='html_radio']").is(":checked")

라디오 그룹의 모든 항목이 선택되지 않은 경우 FALSE를 반환하고 항목이 선택되면 TRUE를 반환합니다.


다음과 같이 할 수 있습니다.

var radio_buttons = $("input[name='html_elements']");
if( radio_buttons.filter(':checked').length == 0){
  // None checked
} else {
  // If you need to use the result you can do so without
  // another (costly) jQuery selector call:
  var val = radio_buttons.val();
}

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

사용 .length을 참조 http://api.jquery.com/checked-selector/

if ($('input[name="html_elements"]:checked').length === 0) alert("Not checked");
else alert("Checked");

나는 이것이 라디오 그룹의 라디오가 확인되었는지 확인하는 간단한 예라고 생각합니다.

if($('input[name=html_elements]:checked').length){
    //a radio button was checked
}else{
    //there was no radio button checked
} 

var len = $('#your_form_id input:radio:checked').length;
      if (!len) {
        alert("None checked");
      };
      alert("checked: "+ len);

이렇게 간단하게 사용하고 있습니다

HTML

<label class="radio"><input id="job1" type="radio" name="job" value="1" checked>New Job</label>
<label class="radio"><input id="job2" type="radio" name="job" value="2">Updating Job</label>


<button type="button" class="btn btn-primary" onclick="save();">Save</button>

스크립트

 $('#save').on('click', function(e) {
    if (job1.checked)
        {
              alert("New Job"); 
        }
if (job2.checked)
        {
            alert("Updating Job");
        }

}

참고 URL : https://stackoverflow.com/questions/2072249/using-jquery-to-check-if-no-radio-button-in-a-group-has-been-checked

반응형