0

I'm using jQuery to show and hide a div. But even in true case else condition executes. I wonder what is my mistake. Thanks for any help in advance.

$(".budget").on("change",function () {
  var radioValue = $(".budget:checked").val();
  if (radioValue=="haveBudget") {
    alert($(this).val());   
  } else {
    alert("else part");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="radio" name="pref" class="budget" value="haveBudget" />
<input type="radio" name="pref" class="budget" value="10" />
yunzen
  • 32,854
  • 11
  • 73
  • 106
aishazafar
  • 1,024
  • 3
  • 15
  • 35

2 Answers2

0

You need to make some basic changes in your code:

// it's better to use event delegation
$(document).on("change", ".budget", function () {
    var radioValue = this.value; // <-- You have the value because "this" is the input
    
    if( radioValue == 'haveBudget' ){
        console.log('show DIV');
        // do whatever.. show your DIV
    }
    else{
        console.log('hide DIV');
    }
    
    console.log("---- value selected ----", radioValue);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label>
  <input type="radio" name="pref" class="budget" value="haveBudget" />
  <span>Have Budget</span>
</label>

<label>
  <input type="radio" name="pref" class="budget" value="10" />
  <span>10</span>
</label>

Learn more about Event Delegation

vsync
  • 118,978
  • 58
  • 307
  • 400
0

$(".budget").on("change",function () {
  var radioValue = $(this).val();
  if (radioValue=="haveBudget") {
    alert($(this).val());   
  } else {
    alert("else part");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="radio" name="pref" class="budget" value="haveBudget" />haveBudget
<input type="radio" name="pref" class="budget" value="10" />10

Use this for accessing value from current object.

Sumesh TG
  • 2,557
  • 2
  • 15
  • 29