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
  • 31,553
  • 11
  • 69
  • 98
aishazafar
  • 864
  • 3
  • 12
  • 34

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
  • 103,437
  • 51
  • 275
  • 359
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,441
  • 1
  • 13
  • 29