It does not work because there is a logic error there. When using $("[name='periodo']").val()
you are taking the value of the first element name='periodo'
on the page, which in this case is semanal
.
Soon, $("[name='periodo']").val()
is not equal to undefined
, is equal to semanal
, therefore does not satisfy the condition of if
.
What you should do is just add :checked
to the selector, as this will return the value of the checked radio, and if none is checked, then it will be undefined
:
function checkRadioPeriodo() {
if ( $("[name='periodo']:checked").val() == undefined ) {
alert("Escolha um período!");
return false;
}
}
$("#botao").on ("click", function () {
checkRadioPeriodo();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="periodo" value="semanal" /> Semanal
<input type="radio" name="periodo" value="mensal" /> Mensal
<br />
<button id="botao"> Validar </button>
You can also check if it is false, without having to compare with undefined
. Just put a sign !
before the jQuery selector:
if ( !$("[name='periodo']:checked").val() ) {
The sign of !
will invalidate if the value is emptiness, Undefined or 0
(numerical type).
Another way is also using .length
to return how many radios were marked. Return 0
(none has been marked), will invalidate:
if ( !$("[name='periodo']:checked").length ) { // com !
or
if ( $("[name='periodo']:checked").length === 0 ) { // sem !
Why don’t you just put checked on one of the radios?
– Wictor Chaves
What is the purpose of the check? It was not clear in your question.
– sant0will
@santOwill, just answering. it’s a radio button..
– Carlos Rocha