Good evening. There are 2 radiobuttons, how to make a check with if, what is the first one selected?

<input type="radio" name="r" value=l>1<br> <input type="radio" name="r" value=2>2<br> 

    4 answers 4

    the check function checks on pure JS without any libraries, and the check2 function using jQuery

     function check() { var inp = document.getElementsByName('r'); for (var i = 0; i < inp.length; i++) { if (inp[i].type == "radio" && inp[i].checked) { alert("selected: " + inp[i].value); } } } function check2(){ alert("selected: " + $('input[name=r]:checked').val()); } 


       /** * функция isCheck возвращает выбранный элемент на чистом JS без каких-либо библиотек * @param name * @returns {Element} */ function isCheck(name) { return document.querySelector('input[name="' + name + '"]:checked'); } // пример использования: alert(isCheck('r').id); 
       <div> <label class="radio"> <input type="radio" name="r" id="one">первый </label> <label class="radio"> <input type="radio" name="r" id="two" checked>второй </label> </div> 

      • If it doesn't bother you, add an example using the function. - 0xdb
       <input type="radio" name="r" value="l" onchange="check()">1<br/> <input type="radio" name="r" value="2" onchange="check()">2<br/> <script> function check(){ var rarr=document.getElementsByName("r"); if(rarr[0].checked){ //То выбран первый radio } } </script> 
         JavaScript let form = document.querySelector('.formValid'); let gender = document.getElementsByName('gender'); (form.gender.value !== 'on') ? console.log('not chek') : console.log('chek'); 


         <form class="formValid"> <div> <div> <label>Gender*</label> </div> <div> Female<input type="radio" name="gender"> Male<input type="radio" name="gender"> </div> </div> </form>