j查询更改功能将无法按预期工作

jQuery on change function won't work as intended

本文关键字:工作 查询 功能      更新时间:2023-09-26

我正在构建一个付款表单,向用户显示的总金额取决于他们在表单顶部选择的计划。但是我没有正确编写它,因为当我选中任何一个单选按钮时没有任何反应。

这是计划选择器代码中的一个片段:

<form id="payment-form" ...>
...
<label class='control-label'>Plan</label><br>
<input type='radio' name='Product' value='Pro Monthly' checked> Monthly
<input type='radio' name='Product' value='Lifetime'> Lifetime

此代码段是向用户显示的总金额:

Total: <span class='amount'></span>

这是我编写的jQuery,用于将应付金额添加到该跨度:

$('#payment-form input').on('change', function () {
     var plan = $('input[name=Product]:checked', '#payment-form').val();
     if (plan == "Lifetime") {
         var price = "&pound;30";
     } else if (plan == "Pro Monthly") {
         var price = "&pound;3 a month";
     }
     $("span.amount").html(price);
});

如果有人能告诉我我做错了什么,我将不胜感激。

请查看我创建的 plunker。

$(document).ready(function() {
$('#payment-form input').on('change', function() {
  var price;
  var plan = $('input[name=Product]:checked', '#payment-form').val();
  if (plan == "Lifetime") {
  price = "30";
  alert(price);
} else if (plan == "Pro Monthly") {
  price = "3 a month";
}
$("#amount").html(price);
 });
});
http://plnkr.co/edit/roUrBSStRbN9aKuJ5vIK

应在 document.ready 中注册事件绑定。

$('#payment-form input').on('change', function () {
 if ($("input[name='Product']:checked").val() == 'Lifetime') {
 var price = "&pound;30";
 } else if ($("input[name='Product']:checked").val() == 'Pro Monthly') {
 var price = "&pound;3 a month";
 }
 $("span.amount").html(price);
});

演示

试试这段代码:

结果会来:

<form id="payment-form">
<label class='control-label'>Plan</label><br>
    <input type='radio' name='Product' value='Pro Monthly' checked/> Monthly
    <input type='radio' name='Product' value='Lifetime'/> Lifetime
</form>
Total: <span class='amount'></span>

.JS:

$(document).ready(function(){
$('#payment-form input').on('change', function () {
var plan = $('input[name=Product]:checked', '#payment-form').val();
if (plan == "Lifetime") {
    var price = "&pound;30";
} else if (plan == "Pro Monthly") {
    var price = "&pound;3 a month";
}
$("span.amount").html(price);
});
}):

供参考演示