jQuery does not return value

Asked

Viewed 64 times

-2

I have the following code below:

  function checkRadioPeriodo() {
		
       if ( $("[name='periodo']").val() == undefined ) {
			
          alert("Escolha um período!");
          return false;

       }

    }
    
    $("#botao").on ("click", function () {
          checkRadioPeriodo();
    }) 
<script src="https://ajax.googleapis.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>

Why doesn’t it work?

Obs.: Validation by name and not by id is needed here.

  • Why don’t you just put checked on one of the radios?

  • What is the purpose of the check? It was not clear in your question.

  • @santOwill, just answering. it’s a radio button..

4 answers

2


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 !
  • 1

    this is the answer I wanted: synthetic and complete. Thank you.

0

It wasn’t very clear your intention with the code.

But try this, from what I understand you want to check if any of the options has been selected:

function checkRadioPeriodo() {
  let $periodos = $('input:radio[name=periodo]');

  if($periodos.is(':checked') === false) {
    alert("Escolha um período!");
  }
}

    
$("#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>

Good is that. Remembering that with pure javascript you do all this without many difficulties too.

  • the negative is! $("[name='periodo']"). is(':checked') ?

  • $periodos.is(':checked') === true // to check if it is checked $periodos.is(':checked') === false // to check that it is not checked

0

Better test the element for verification. use this version of the function in your footer:

function checkRadioPeriodo() {          
       if ( $('input[name="periodo"]').is(':checked') ) {               
          console.log("checado!");
          return false;
       }else{
        console.log("Não selecionado!");
          return false;
       }
    }       
    $("#botao").on("click", function (){
        checkRadioPeriodo();
    });
  • the negative is! $("[name='periodo']"). is(':checked') ?

  • The correct negative is: !( $('input[name="periodo"]').is(':checked') ), because in that way one checks the return of is().

-1

I don’t quite understand what you want, but I’ll try to help anyway. You’re only returning something when you don’t select either one... do so:

  function checkRadioPeriodo() {
		
       if ( $("[name='periodo']").val() == undefined ) {
			
          alert("Escolha um período!");
          return false;

       }else{
         return $("[name='periodo']").val();
       }

    }
    
    $("#botao").on ("click", function () {
          checkRadioPeriodo();
    }) 
<script src="https://ajax.googleapis.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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.