JavaScript로 라디오 버튼이 선택되었는지 어떻게 확인할 수 있습니까?


답변:


330

이런 HTML이 있다고 가정 해 봅시다

<input type="radio" name="gender" id="gender_Male" value="Male" />
<input type="radio" name="gender" id="gender_Female" value="Female" />

클라이언트 측 유효성 검사를 위해 선택된 Javascript를 확인하는 Javascript가 있습니다.

if(document.getElementById('gender_Male').checked) {
  //Male radio button is checked
}else if(document.getElementById('gender_Female').checked) {
  //Female radio button is checked
}

위의 내용은 마크 업의 정확한 특성에 따라 더 효율적으로 만들 수 있지만 시작하기에 충분해야합니다.


페이지의 아무 곳 이나 라디오 버튼이 선택 되어 있는지 확인하려는 경우 PrototypeJS를 사용하면 매우 쉽습니다.

다음은 페이지에서 하나 이상의 단일 선택 단추가 선택된 경우 true를 리턴하는 함수입니다. 다시 말하지만 특정 HTML에 따라 조정해야 할 수도 있습니다.

function atLeastOneRadio() {
    return ($('input[type=radio]:checked').size() > 0);
}

서버 측 유효성 검사 ( 유효성을 위해 Javascript에만 전적으로 의존 할 수는 없습니다!) 의 경우 선택한 언어에 따라 다르지만 gender요청 문자열 의 값을 확인 합니다.


1
그러나 선택한 항목에 관계없이 라디오 버튼이 선택되어 있는지 확인하고 싶습니다.
— noob

1
나는 당신이 말하는 것을 정말로 따르지 않습니까? 모든 라디오 버튼의 선택 여부에 관심이 있습니까?
— Mark Biek

예. 단일 선택 단추를 포함하여 모든 필드가 채워지지 않으면 양식을 제출할 수 없기 때문입니다.
— noob

if (document.getElementById ( 'gender_Male'). checked || document.getElementById ( 'gender_Female'). checked) alert ( '일부 라디오 박스가 확인되었습니다');
— Havenard

R. Bemrose에서 방금 배운 CSS 선택기 수업을 활용하기 위해 프로토 타입 예제를 수정했습니다.
— Mark Biek

111

jQuery를 사용하면 다음과 같습니다.

if ($('input[name=gender]:checked').length > 0) {
    // do something here
}

좀 더 명확하게 다루기 위해 조각으로 나눕니다. jQuery는 왼쪽에서 오른쪽으로 사물을 처리합니다.

input[name=gender]:checked
  1. input 입력 태그로 제한합니다.
  2. [name=gender] 이전 그룹 내에서 성별이 성별 인 태그로 제한합니다.
  3. :checked 이전 그룹 내에서 선택된 확인란 / 라디오 버튼으로 제한합니다.

이를 피 checked="checked"하려면 HTML 코드에서 라디오 버튼 중 하나를 선택 ( )으로 표시하십시오. 그러면 라디오 버튼 하나가 항상 선택됩니다.


17
unsked 상태에서 라이브러리를 제안하는 경우 -1입니다. 이 방법으로 "라이브러리 x 포함, x.doWhatYouNNed () 사용"으로 모든 것에 응답 할 수 있습니다. 화염의 의도는 없습니다. 저는이 질문에 순수한 자바 스크립트로 답해야한다고 생각합니다. (그리고 결국 라이브러리가 얼마나 쉬운 지 지적하십시오)
— Riccardo Galli

23
@RiccardoGalli : 많은 사람들이 이미 jQuery를 사용하고 있습니다. 따라서 왜 이미 jQuery를 사용하고 있다면 "jQuery를 사용하면 이런 식으로 될 것"으로 시작합니다.
— Powerlord

1
이 같은 선택기를 연결할 수 있는지 아는 사람이 있습니까? 추가 검증을 위해 input [name = gender] [type = radio] 또는 input [name = gender, type = radio]?
— Ty_

@ EW-CodeMonkey 당신이 언급 한 첫 번째 방법 이 작동 합니다.
— Powerlord

81

바닐라 자바 ​​스크립트 방식

var radios = document.getElementsByTagName('input');
var value;
for (var i = 0; i < radios.length; i++) {
    if (radios[i].type === 'radio' && radios[i].checked) {
        // get value, set checked flag or do whatever you need to
        value = radios[i].value;       
    }
}

2
그런데 지금은 거의 동일한 문제를 가지고 당신의 코드는 매우 helpfull했다
— MoreThanChaos

2
마지막으로 확인한 라디오 버튼의 값을 얻을 수 있습니다. 라디오 그룹이 여러 개인 경우 올바른 값을 얻지 못할 수 있습니다.
— styfle

@styfle 이것은 페이지에 양식에 라디오 버튼이 두 개뿐이라는 OP의 질문에 잘 작동합니다. 해결책은 두 개 이상의 라디오 버튼, 여러 라디오 그룹 등과 같은 다른 문제 시나리오에 따라 다를 수 있습니다. :)
— Russ Cam

2
@RussCam 예, 라디오 버튼이 2 개인 작은 페이지에서 작동하지만 답변을 완성하기 위해 의견을 추가했습니다. 라디오 버튼 요소를 얻는 가장 좋은 방법은 name입니다.
— styfle

더 좋은 방법은 특정 클래스별로 라디오 요소를 선택한 다음 다른 라디오 요소 그룹을 다른 클래스로 그룹화하는 것입니다. 그렇지 않으면이 솔루션은 다른 입력 양식 요소가없는 하나의 무선 요소 그룹에서만 작동합니다.
— Oliver

15

그냥 바닐라 JavaScript로 던져진 CSS 선택기 설탕 으로 Russ Cam의 솔루션 을 개선하려고했습니다 .

var radios = document.querySelectorAll('input[type="radio"]:checked');
var value = radios.length>0? radios[0].value: null;

여기서 jQuery가 실제로 필요하지 않습니다. querySelectorAll은 현재 충분히 널리 지원됩니다.

편집 : CSS 선택기로 버그가 수정되었습니다. 따옴표를 생략 할 수는 있지만 생략 할 수는 있지만 어떤 경우에는 인용 부호를 남겨 두는 것이 좋습니다.


var radios = document.querySelectorAll ( 'input [type = "radio"] : checked')이어야합니다.;
— Md. Shafiqur Rahman

@ShafiqurRahman 당신은 절대적으로 맞습니다. 내 대답을 업데이트 할 것입니다. 라디오 주위에 따옴표가 필요하다고 생각하지 않습니다.
— Matt McCabe

3
Vanilla JavaScript의 경우 +1 다른 속성 값 (예 :)의 경우에는 값 a[href^="http://"]이 필요하고 일관성을 유지 관리하기 쉽기 때문에 항상 속성 값 주위에 따옴표를 사용합니다 . 또한 속성 선언이 해당 HTML과 일치하도록합니다.
— Manngo

11

HTML 코드

<input type="radio" name="offline_payment_method" value="Cheque" >
<input type="radio" name="offline_payment_method" value="Wire Transfer" >

자바 스크립트 코드 :

var off_payment_method = document.getElementsByName('offline_payment_method');
var ischecked_method = false;
for ( var i = 0; i < off_payment_method.length; i++) {
    if(off_payment_method[i].checked) {
        ischecked_method = true;
        break;
    }
}
if(!ischecked_method)   { //payment method button is not checked
    alert("Please choose Offline Payment Method");
}

2
경고 :이 코드는 페이지가로드되는 즉시 팝업 경고를 반환합니다.
— samthebrand

11

이 간단한 스크립트를 사용할 수 있습니다. 이름과 값이 다른 라디오 버튼 이 여러 개 있을 수 있습니다 .

var checked_gender = document.querySelector('input[name = "gender"]:checked');

if(checked_gender != null){  //Test if something was checked
alert(checked_gender.value); //Alert the value of the checked.
} else {
alert('Nothing checked'); //Alert, nothing was checked.
}

+1. 이것은 확인 된 무선 요소를 얻는 가장 짧은 Vanilla JS 솔루션입니다. 나는 이것이 당신에게 가장 좋은 대답이라고 생각합니다. 가치를 얻기 위해서만 사용할 수 있습니다document.forms[0].elements['nameOfRadioList'].value
— Bharata

9

이 페이지의 스크립트는 아래 스크립트를 작성하는 데 도움이되었으며,이 스크립트는보다 완전하고 보편적이라고 생각합니다. 기본적으로 양식의 라디오 버튼 수를 확인하므로 양식 내의 다른 라디오 그룹 각각에 대해 라디오 옵션이 선택되어 있어야합니다. 예를 들어 아래 시험 양식에서 :

   <form id="FormID">

    Yes <input type="radio" name="test1" value="Yes">
    No <input type="radio" name="test1" value="No">

    <br><br>

    Yes <input type="radio" name="test2" value="Yes">
    No <input type="radio" name="test2" value="No">

   <input type="submit" onclick="return RadioValidator();">

RadioValidator 스크립트는 제출하기 전에 'test1'과 'test2'모두에 대한 답변이 제공되었는지 확인합니다. 양식에 라디오 그룹을 여러 개 가질 수 있으며 다른 양식 요소는 무시합니다. 누락 된 모든 라디오 응답은 단일 경고 팝업 내에 표시됩니다. 여기 사람들에게 도움이 되길 바랍니다. 모든 버그 수정 또는 유용한 수정을 환영합니다 :)

<SCRIPT LANGUAGE="JAVASCRIPT">
function RadioValidator()
{
    var ShowAlert = '';
    var AllFormElements = window.document.getElementById("FormID").elements;
    for (i = 0; i < AllFormElements.length; i++) 
    {
        if (AllFormElements[i].type == 'radio') 
        {
            var ThisRadio = AllFormElements[i].name;
            var ThisChecked = 'No';
            var AllRadioOptions = document.getElementsByName(ThisRadio);
            for (x = 0; x < AllRadioOptions.length; x++)
            {
                 if (AllRadioOptions[x].checked && ThisChecked == 'No')
                 {
                     ThisChecked = 'Yes';
                     break;
                 } 
            }   
            var AlreadySearched = ShowAlert.indexOf(ThisRadio);
            if (ThisChecked == 'No' && AlreadySearched == -1)
            {
            ShowAlert = ShowAlert + ThisRadio + ' radio button must be answered\n';
            }     
        }
    }
    if (ShowAlert != '')
    {
    alert(ShowAlert);
    return false;
    }
    else
    {
    return true;
    }
}
</SCRIPT>

6

라디오 입력 값을 가져올 때 jQuery와 함께이 동작에 유의하십시오.

$('input[name="myRadio"]').change(function(e) { // Select the radio input group

    // This returns the value of the checked radio button
    // which triggered the event.
    console.log( $(this).val() ); 

    // but this will return the first radio button's value,
    // regardless of checked state of the radio group.
    console.log( $('input[name="myRadio"]').val() ); 

});

따라서 $('input[name="myRadio"]').val()예상대로 라디오 입력의 확인 된 값을 반환하지 않습니다. 첫 번째 라디오 버튼의 값을 반환합니다.


4

mootools 사용 ( http://mootools.net/docs/core/Element/Element )

html :

<input type="radio" name="radiosname" value="1" />
<input type="radio" name="radiosname" value="2" id="radiowithval2"/>
<input type="radio" name="radiosname" value="3" />

js :

// Check if second radio is selected (by id)
if ($('radiowithval2').get("checked"))

// Check if third radio is selected (by name and value)
if ($$('input[name=radiosname][value=3]:checked').length == 1)


// Check if something in radio group is choosen
if ($$('input[name=radiosname]:checked').length > 0)


// Set second button selected (by id)
$("radiowithval2").set("checked", true)

// ($$ ( 'input [name = radiosname] : checked'). length> 0)이 정확히 필요한 경우 라디오 그룹의 항목이 선택되었는지 확인
— Steve Johnson

3

이것은이 문제를 해결하기 위해 만든 유틸리티 함수입니다.

    //define radio buttons, each with a common 'name' and distinct 'id'. 
    //       eg- <input type="radio" name="storageGroup" id="localStorage">
    //           <input type="radio" name="storageGroup" id="sessionStorage">
    //param-sGroupName: 'name' of the group. eg- "storageGroup"
    //return: 'id' of the checked radioButton. eg- "localStorage"
    //return: can be 'undefined'- be sure to check for that
    function checkedRadioBtn(sGroupName)
    {   
        var group = document.getElementsByName(sGroupName);

        for ( var i = 0; i < group.length; i++) {
            if (group.item(i).checked) {
                return group.item(i).id;
            } else if (group[0].type !== 'radio') {
                //if you find any in the group not a radio button return null
                return null;
            }
        }
    }

1
재사용 성과 단순성 때문에 이와 같습니다. 또한 반환 값은 멋진 switch 문으로 처리 할 수 ​​있습니다.
— JGurtz

3

이것은 JQuery가 필요없는 동일한 이름을 공유하는 라디오 버튼에 유효합니다.

var x = Array.prototype.filter.call(document.getElementsByName('checkThing'), function(x) { return x.checked })[0];

우리가 체크 박스에 대해 이야기하고 체크 박스가 체크 된 이름을 공유하는 목록을 원한다면 :

var x = Array.prototype.filter.call(document.getElementsByName('checkThing'), function(x) { return x.checked });

3
if(document.querySelectorAll('input[type="radio"][name="name_of_radio"]:checked').length < 1)

2

Mark Biek에 대한 약간의 수정.

HTML 코드

<form name="frm1" action="" method="post">
  <input type="radio" name="gender" id="gender_Male" value="Male" />
  <input type="radio" name="gender" id="gender_Female" value="Female" / >
  <input type="button" value="test"  onclick="check1();"/>
</form>

및 라디오 버튼이 선택되어 있는지 확인하는 Javascript 코드

<script type="text/javascript">
    function check1() {            
        var radio_check_val = "";
        for (i = 0; i < document.getElementsByName('gender').length; i++) {
            if (document.getElementsByName('gender')[i].checked) {
                alert("this radio button was clicked: " + document.getElementsByName('gender')[i].value);
                radio_check_val = document.getElementsByName('gender')[i].value;        
            }        
        }
        if (radio_check_val === "")
        {
            alert("please select radio button");
        }        
    }
</script>

1
getElementsByName ()은 HTMLCollection을 반환합니다.이 속성은 checked 속성이 없으므로 게시 한 JavaScript 스 니펫이 의도 한대로 작동하지 않는다고 생각합니다. 다른 사람들이 제안한대로 HTMLCollection의 요소를 반복하여 검사해야합니다.
— Rudi

감사. 더 이상 사람들이 잘못된 정보를 얻지 못하도록 내 대답을 업데이트했습니다.
— Parag

2

ECMA6 및 method로 라디오 버튼을 확인했는지 여부를 검증 할 수있는 매우 정교한 방법이 있습니다 .some().

HTML :

<input type="radio" name="status" id="marriedId" value="Married" />
<input type="radio" name="status" id="divorcedId" value="Divorced" />

그리고 자바 스크립트 :

let htmlNodes = document.getElementsByName('status');

let radioButtonsArray = Array.from(htmlNodes);

let isAnyRadioButtonChecked = radioButtonsArray.some(element => element.checked);

isAnyRadioButtonChecked될 것입니다 true라디오 버튼 중 일부를 체크하는 경우 false그 중 어느 것도 선택하는 경우.


2

라디오 버튼에 체크 된 모든 요소를 ​​반환

  Array.from(document.getElementsByClassName("className")).filter(x=>x['checked']);

1

http://www.somacon.com/p143.php/

function getCheckedValue(radioObj) {
    if(!radioObj)
        return "";
    var radioLength = radioObj.length;
    if(radioLength == undefined)
        if(radioObj.checked)
            return radioObj.value;
        else
            return "";
    for(var i = 0; i < radioLength; i++) {
        if(radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
}

1

JQuery를 사용하여 라디오 버튼의 현재 상태를 확인하는 또 다른 방법은 속성을 'checked'하는 것입니다.

예를 들어 :

<input type="radio" name="gender_male" value="Male" />
<input type="radio" name="gender_female" value="Female" />

이 경우 다음을 사용하여 버튼을 확인할 수 있습니다.

if ($("#gender_male").attr("checked") == true) {
...
}

1
필자의 경우 값은 부울이 아닌 $("#gender_male").attr("checked")문자열 "checked"입니다.
— Koks_rs

1

이 코드는 양식이 제출 될 때 선택된 단일 선택 단추에 경고합니다. 선택된 값을 얻기 위해 jQuery를 사용했습니다.

$("form").submit(function(e) {
  e.preventDefault();
  $this = $(this);

  var value = $this.find('input:radio[name=COLOR]:checked').val();
  alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input name="COLOR" id="Rojo" type="radio" value="red">
  <input name="COLOR" id="Azul" type="radio" value="blue">
  <input name="COLOR" id="Amarillo" type="radio" value="yellow">
  <br>
  <input type="submit" value="Submit">
</form>


1

내가 사용 확산 운영자 및 일부 는 배열에서 하나 이상의 요소를 검사하여 테스트를 통과했습니다.

나는 누구의 관심사를 공유합니다.

var checked = [...document.getElementsByName("gender")].some(c=>c.checked);
console.log(checked);
<input type="radio" name="gender" checked value="Male" />
<input type="radio" name="gender"  value="Female" / >


0

다음은 제출을 진행하지 않고 라디오 버튼을 선택하지 않은 경우 경고를 보내도록 확장 된 솔루션입니다. 물론 이것은 시작하기 위해 체크를 해제해야 함을 의미합니다!

if(document.getElementById('radio1').checked) {
} else if(document.getElementById('radio2').checked) {
} else {
  alert ("You must select a button");
  return false;
}

각 라디오 버튼의 형식으로 id ( 'radio1', 'radio2'또는 무엇이든 호출)를 설정하면 스크립트가 작동하지 않습니다.


당신은 간단하게 할 수 있습니다 : if (!document.getElementById('radio1').checked && !document.getElementById('radio2').checked) { alert(); }.
— insertusernamehere 여기에

0

예를 들면 :

if (!checkRadioArray(document.ExamEntry.level)) { 
    msg+="What is your level of entry? \n"; 
    document.getElementById('entry').style.color="red"; 
    result = false; 
} 

if(msg==""){ 
    return result;  
} 
else{ 
    alert(msg) 
    return result;
} 

function Radio() { 
    var level = radio.value; 
    alert("Your level is: " + level + " \nIf this is not the level your taking then please choose another.") 
} 

function checkRadioArray(radioButtons) { 
    for(var r=0;r < radioButtons.length; r++) { 
        if (radioButtons[r].checked) { 
            return true; 
        } 
    } 
    return false; 
} 


0

jQuery를 사용하여 무언가 를 선택 하고 싶습니다 .

// html
<input name="gender" type="radio" value="M" /> Male <input name="gender" type="radio" value="F" /> Female

// gender (required)
var gender_check = $('input:radio[name=gender]:checked').val();
if ( !gender_check ) {
    alert("Please select your gender.");
    return false;
}

0

바닐라 자바 ​​스크립트를 원한다면 각 라디오 버튼에 ID를 추가하여 마크 업을 어지럽히 지 않고 최신 브라우저 만 신경 쓰면 다음과 같은 기능적 접근 방식이 for 루프보다 조금 더 맛있습니다.

<form id="myForm">
<label>Who will be left?
  <label><input type="radio" name="output" value="knight" />Kurgan</label>
  <label><input type="radio" name="output" value="highlander" checked />Connor</label>
</label>
</form>

<script>
function getSelectedRadioValue (formElement, radioName) {
    return ([].slice.call(formElement[radioName]).filter(function (radio) {
        return radio.checked;
    }).pop() || {}).value;
}

var formEl = document.getElementById('myForm');
alert(
   getSelectedRadioValue(formEl, 'output') // 'highlander'
)
</script>

둘 다 선택하지 않으면 반환됩니다 undefined(위의 줄을 변경하여 다른 것을 반환 할 수는 있지만 false반환 하기 위해 위의 관련 줄을 다음과 같이 변경할 수 있습니다).}).pop() || {value:false}).value; ).

RadioNodeList 인터페이스는 value양식 하위 라디오 요소 (위의 코드에서로 formElement[radioName]표시됨) 목록의 속성을 쉽게 사용할 수 있어야 하기 때문에 미래 지향적 인 폴리 필 접근 방식도 있지만 고유 한 문제가 있습니다. RadioNodeList를 폴리 필하는 방법 ?


0

이것은 요소 ID를 호출하지 않고 배열 요소로 사용하여 호출하면서 작동합니다.

다음 코드는 radiobuttons 그룹으로 명명 된 배열이 html 문서에서 선언 된 것과 동일한 순서로 radiobuttons 요소로 구성되어 있다는 사실을 기반으로합니다.

if(!document.yourformname.yourradioname[0].checked 
   && !document.yourformname.yourradioname[1].checked){
    alert('is this working for all?');
    return false;
}

0

HTML :

<label class="block"><input type="radio" name="calculation" value="add">+</label>
<label class="block"><input type="radio" name="calculation" value="sub">-</label>
<label class="block"><input type="radio" name="calculation" value="mul">*</label>
<label class="block"><input type="radio" name="calculation" value="div">/</label>

<p id="result"></p>

자바 스크립트 :

var options = document.getElementsByName("calculation");

for (var i = 0; i < options.length; i++) {
    if (options[i].checked) {
        // do whatever you want with the checked radio
        var calc = options[i].value;
        }
    }
    if(typeof calc == "undefined"){
        document.getElementById("result").innerHTML = " select the operation you want to perform";
        return false;
}

-2

이름은 같지만 ID가 다른 라디오 버튼을 제공하십시오.

var verified1 = $('#SOME_ELEMENT1').val();
var verified2 = $('#SOME_ELEMENT2').val();
var final_answer = null;
if( $('#SOME_ELEMENT1').attr('checked') == 'checked' ){
  //condition
  final_answer = verified1;
}
else
{
  if($('#SOME_ELEMENT2').attr('checked') == 'checked'){
    //condition
    final_answer = verified2;
   }
   else
   {
     return false;
   }
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.