3

我正在尝试选择一组单选按钮的值并使用它来设置变量。这个想法是每次更改单选按钮时变量都会更改。

由于某种原因,这似乎不起作用,我不知道为什么。该变量似乎没有从最初定义的“0”改变。按下黄色按钮时,变量应显示在警告框中。

我已经整理了我想要实现的简化版本 - 见下文。

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 var paytype = 0;

 $("input [name = paytype]").change(function(){
  var paytype = $(this).val();
  });

 $("#button").click(function(){
  alert ( paytype );
  });
 });
</script>

</head>
<body>
<form id="enrolmentform" action="thanks.php">

<input type="radio" name="paytype" id="bacs" value="Bank Transfer" />
<label for="bacs">Bank Payment/BACS Transfer</label>
<input type="radio" name="paytype" id="cheque" value="Cheque" />
<label for="cheque">Cheque</label>
<input type="radio" name="paytype" id="card" value="Card" />
<label for="card">Card</label>

<div style="width:45px; height: 20px; background-color: yellow; border: thin solid black; margin-top: 20px;"><a href="#" id="button">Button</a></div>
</form>

</body>
</html>

非常感谢任何帮助。

谢谢!

4

5 回答 5

6

您两次声明付款类型。你不需要var

$("input [name = paytype]").change(function(){
    paytype = $(this).val();
});
于 2012-10-10T11:22:25.893 回答
2

请试试这个

$("input:radio[name='paytype']").change(function(){
 paytype = $(this).val();
});  

小提琴链接

于 2012-10-10T11:25:28.180 回答
0

你在这一行重新定义你的变量

var paytype = $(this).val();

将其替换为

paytype = $(this).val();
于 2012-10-10T11:23:00.387 回答
0
$(document).ready(function(){
 var paytype = 0;

 $("input [name = paytype]").change(function(){
  paytype = $(this).val();
  });

 $("#button").click(function(){
  alert ( paytype );
  });
 });
于 2012-10-10T11:23:18.310 回答
0

你去吧,有几个小错误..

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">            </script>
<script type="text/javascript">
$(document).ready(function(){
 var paytype;

 $("input[name='paytype']").change(function(){
   paytype = $(this).val();
  });

 $("#button").click(function(){
  alert ( paytype );
  });
 });
</script>

</head>
<body>
<form id="enrolmentform" action="thanks.php">

<input type="radio" name="paytype" id="bacs" value="Bank Transfer" />
<label for="bacs">Bank Payment/BACS Transfer</label>
<input type="radio" name="paytype" id="cheque" value="Cheque" />
<label for="cheque">Cheque</label>
<input type="radio" name="paytype" id="card" value="Card" />
<label for="card">Card</label>

<div style="width:45px; height: 20px; background-color: yellow; border: thin solid     black; margin-top: 20px;"><a href="#" id="button">Button</a></div>
</form>

</body>
</html>
于 2012-10-10T11:28:18.083 回答