jQuery单选按钮问题

时间:2018-11-26 13:41:20

标签: javascript jquery

我正在使用jQuery显示和隐藏div。但是即使在真实情况下,条件也会执行。我想知道我的错误是什么。感谢您的任何提前帮助。

$(".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" />

2 个答案:

答案 0 :(得分:0)

您需要对代码进行一些基本更改:

// 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>

详细了解Event Delegation

答案 1 :(得分: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

使用this访问当前对象的值。