Get the value of the Jquery variable outside of if

3

I'm putting together a script that checks multiple select inputs, verifying that 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 out, it does not work.

If it works out, I want to make a var, adding all the values. If you give 0, you need to fill in some of the fields, otherwise, go to the next screen. There is 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 click event.

But I do not understand why he does not take value the way I did.

    
asked by anonymous 24.08.2017 / 14:43

3 answers

3

You are declaring the variable within a function in click so only the alert works within $("#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);	
});			
    
24.08.2017 / 14:50
2

Problem explanation: If you declared the variable his within if or else is indifferent the problem is that the variable his in your code only exists within the scope of the function of your click $("#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><buttontype="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>
    
24.08.2017 / 15:00
0

Friend, the problem is that your his variable is out of the click function! Declare his variable outside the context of the click 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);
    
24.08.2017 / 14:51