Take the value of the Jquery variable out of if

Asked

Viewed 261 times

3

I am assembling a script that checks several inputs select, checking whether they have been selected. I’m at the beginning, so the example here has only one field.

$("#passo_4").click(function(){
  if($("#horario_ini_seg option:selected").val() == ''){
    var his = 0;
   }	else{
    var his = 1;
  }		
});			
alert(his);

If I put the Alert under each var, it works. If I put it away, it doesn’t work.

If it works, I want to do a var, adding up all the values. If you give 0, you need to fill in some of the fields, otherwise, move to the next screen. There’s a checkbox that I need to do the same, but I think it’s the same case.

There are 14 inputs.

My idea is to check everyone in the event click.

But I don’t understand why he doesn’t take the value the way I did.

  • 1

    you are declaring the variable inside the if so only works under each value

3 answers

3


You are declaring the variable within a function in the click so it only works the Alert inside the $("#passo_4").click(function(){});

 var his = 0;
$("#passo_4").click(function(){
  
  if($("#horario_ini_seg option:selected").val() == ''){
     his = 0;
   }	else{
     his = 1;
  }	
  alert(his);	
});			

  • It worked. Thank you very much!!

  • It was nothing !!

2

Explanation of the problem: If you declared his variable within the if or Else is indifferent the problem is that the variable his in your code only exists within the scope of your click function $("#passo_4").click(function(){});.

var his;

$("#passo_4").click(function(){
  if($("#horario_ini_seg option:selected").val() == ''){
    his = 0;
   }else{
    his = 1;
  }		
});		

alert(his); //Só será exibido quando carregar e trará o valor  inicial nesse caso undefined

//Criei o bloco abaixo só para demonstrar o alert com a variavel his fora do evento click do botão passo_4:
$("#passo_5").click(function(){
  alert(his);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="passo_4">Pedir café</button>
<select name="horario_ini_seg" id="horario_ini_seg">
  <option value="">Café forte</option>
  <option value="Zuado">Café fraco</option>
</select>
<button type="button" id="passo_5">Exibe variavel his</button>

0

Friend, the problem is that your variable his is out of click function! Declare the variable his out of click context that works

var his = 0;
$("#passo_4").click(function(){
  if($("#horario_ini_seg option:selected").val() == ''){
    var his = 0;
   }    else{
    var his = 1;
  }     
});         
alert(his);

Browser other questions tagged

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