Respostas:
Vamos fingir que você tem HTML assim
<input type="radio" name="gender" id="gender_Male" value="Male" />
<input type="radio" name="gender" id="gender_Female" value="Female" />
Para validação do lado do cliente, veja alguns Javascript para verificar qual deles está selecionado:
if(document.getElementById('gender_Male').checked) {
//Male radio button is checked
}else if(document.getElementById('gender_Female').checked) {
//Female radio button is checked
}
O exposto acima pode ser mais eficiente, dependendo da natureza exata da sua marcação, mas isso deve ser suficiente para você começar.
Se você está apenas olhando para ver se algum botão de opção está selecionado em qualquer lugar da página, o PrototypeJS facilita muito.
Aqui está uma função que retornará true se pelo menos um botão de opção estiver selecionado em algum lugar da página. Novamente, isso pode precisar ser ajustado dependendo do seu HTML específico.
function atLeastOneRadio() {
return ($('input[type=radio]:checked').size() > 0);
}
Para a validação no servidor (lembre-se, você não pode depender inteiramente do Javascript para validação!) , Isso dependeria do idioma de sua escolha, mas você apenas verificaria o gendervalor da sequência de solicitação.
Com o jQuery , seria algo como
if ($('input[name=gender]:checked').length > 0) {
// do something here
}
Deixe-me dividir isso em pedaços para cobrir mais claramente. O jQuery processa as coisas da esquerda para a direita.
input[name=gender]:checked
input limita a entrada de tags.[name=gender] limita-o a tags com o nome gender no grupo anterior.:checked limita-o a caixas de seleção / botões de opção selecionados no grupo anterior.Se você quiser evitar isso completamente, marque um dos botões de opção como marcado ( checked="checked") no código HTML, o que garantiria que um botão de opção esteja sempre selecionado.
Uma maneira JavaScript baunilha
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;
}
}
name.
Apenas tentando melhorar a solução de Russ Cam com um pouco de açúcar seletor de CSS inserido no JavaScript baunilha.
var radios = document.querySelectorAll('input[type="radio"]:checked');
var value = radios.length>0? radios[0].value: null;
Não há necessidade real de jQuery aqui, o querySelectorAll é amplamente suportado agora.
Edit: corrigido um bug com o seletor css, eu incluí as aspas, embora você possa omiti-las, em alguns casos você não pode, por isso é melhor deixá-las.
a[href^="http://"]) eles seriam necessários e a consistência é mais sustentável. Além disso, isso permite que a declaração do atributo corresponda ao HTML correspondente.
Código HTML
<input type="radio" name="offline_payment_method" value="Cheque" >
<input type="radio" name="offline_payment_method" value="Wire Transfer" >
Código Javascript:
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");
}
Você pode usar esse script simples. Você pode ter vários botões de opção com os mesmos nomes e valores diferentes.
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.
}
document.forms[0].elements['nameOfRadioList'].value
Os scripts desta página me ajudaram a criar o script abaixo, que eu acho mais completo e universal. Basicamente, ele validará qualquer número de botões de opção em um formulário, o que significa que garantirá que uma opção de opção tenha sido selecionada para cada um dos diferentes grupos de opções do formulário. por exemplo, no formulário de teste abaixo:
<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();">
O script RadioValidator garantirá que uma resposta seja dada para 'test1' e 'test2' antes de ser enviada. Você pode ter tantos grupos de rádio no formulário e ele ignorará quaisquer outros elementos do formulário. Todas as respostas de rádio ausentes serão exibidas dentro de um único pop-up de alerta. Aqui vai, espero que ajude as pessoas. Quaisquer correções de erros ou modificações úteis são bem-vindas :)
<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>
Observe esse comportamento com o jQuery ao obter valores de entrada de rádio:
$('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() );
});
Portanto $('input[name="myRadio"]').val(), não retorna o valor verificado da entrada de rádio, como seria de esperar - ele retorna o valor do primeiro botão de opção.
Com 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)
esta é uma função utilitária que eu criei para resolver este problema
//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;
}
}
}
Isso seria válido para botões de opção que compartilham o mesmo nome, não é necessário JQuery.
var x = Array.prototype.filter.call(document.getElementsByName('checkThing'), function(x) { return x.checked })[0];
Se estamos falando de caixas de seleção e queremos uma lista com as caixas de seleção marcadas, compartilhando um nome:
var x = Array.prototype.filter.call(document.getElementsByName('checkThing'), function(x) { return x.checked });
if(document.querySelectorAll('input[type="radio"][name="name_of_radio"]:checked').length < 1)
apenas uma pequena modificação em Mark Biek;
CÓDIGO 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>
e código Javascript para verificar se o botão de opção está selecionado
<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>
Existe uma maneira muito sofisticada de validar se algum dos botões de opção é verificado com o ECMA6 e o método .some().
Html:
<input type="radio" name="status" id="marriedId" value="Married" />
<input type="radio" name="status" id="divorcedId" value="Divorced" />
E javascript:
let htmlNodes = document.getElementsByName('status');
let radioButtonsArray = Array.from(htmlNodes);
let isAnyRadioButtonChecked = radioButtonsArray.some(element => element.checked);
isAnyRadioButtonCheckedserá truese alguns dos botões de opção estiverem marcados e falsese nenhum deles estiver marcado.
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 "";
}
Com o JQuery, outra maneira de verificar o status atual dos botões de opção é obter o atributo 'verificado'.
Por exemplo:
<input type="radio" name="gender_male" value="Male" />
<input type="radio" name="gender_female" value="Female" />
Nesse caso, você pode verificar os botões usando:
if ($("#gender_male").attr("checked") == true) {
...
}
$("#gender_male").attr("checked")é uma string "checked"e não um booleano.
Este código alertará o botão de opção selecionado quando o formulário for enviado. Ele usou o jQuery para obter o valor selecionado.
$("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>
Eu usei o operador spread e alguns para verificar pelo menos um elemento na matriz passa no teste.
Eu compartilho para quem preocupação.
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" / >
Aqui está a solução que é expandida para não prosseguir com o envio e enviar um alerta se os botões de opção não estiverem marcados. É claro que isso significa que você precisa desmarcá-las para começar!
if(document.getElementById('radio1').checked) {
} else if(document.getElementById('radio2').checked) {
} else {
alert ("You must select a button");
return false;
}
Lembre-se de definir o ID ('radio1', 'radio2' ou o que você chamou) no formato de cada um dos botões de opção ou o script não funcionará.
if (!document.getElementById('radio1').checked && !document.getElementById('radio2').checked) { alert(); }.
Um exemplo:
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;
}
A forma
<form name="teenageMutant">
<input type="radio" name="ninjaTurtles"/>
</form>
O script
if(!document.teenageMutant.ninjaTurtles.checked){
alert('get down');
}
O violino: http://jsfiddle.net/PNpUS/
Eu só quero garantir que algo seja selecionado (usando 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;
}
Se você deseja JavaScript de baunilha, não deseja confundir sua marcação adicionando IDs em cada botão de opção e se preocupando apenas com navegadores modernos , a seguinte abordagem funcional é um pouco mais agradável para mim do que um loop 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>
Se nenhum deles estiver marcado, ele retornará undefined(embora você possa alterar a linha acima para retornar outra coisa, por exemplo, para falseretornar, você pode alterar a linha relevante acima para }).pop() || {value:false}).value;:).
Há também a abordagem de polyfill de previsão, uma vez que a interface RadioNodeList deve facilitar o uso de uma valuepropriedade na lista de elementos de rádio filho de formulário (encontrados no código acima como formElement[radioName]), mas que possui seus próprios problemas: Como polifill RadioNodeList ?
Isso também está funcionando, evitando chamar um ID de elemento, mas chamando-o usando como um elemento de matriz.
O código a seguir baseia-se no fato de que uma matriz, denominada grupo de botões de opção, é composta por elementos de botões de opção na mesma ordem em que foram declarados no documento html:
if(!document.yourformname.yourradioname[0].checked
&& !document.yourformname.yourradioname[1].checked){
alert('is this working for all?');
return false;
}
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>
JAVAScript:
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;
}
Dê botões de opção com o mesmo nome, mas com IDs diferentes.
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;
}
}