为什么我不能按名称选择表单元素并使用它们的值来设置jQuery变量

时间:2012-10-10 11:20:25

标签: javascript jquery html

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

由于某些原因,这似乎不起作用,我不知道为什么。变量似乎没有从最初定义的'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>

任何帮助都非常感激。

谢谢!

5 个答案:

答案 0 :(得分:6)

您声明的付款方式两次。您不需要var

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

答案 1 :(得分:2)

请试试这个

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

Fiddle link

答案 2 :(得分:0)

您正在此行中定义变量

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

替换为

paytype = $(this).val();

答案 3 :(得分:0)

$(document).ready(function(){
 var paytype = 0;

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

 $("#button").click(function(){
  alert ( paytype );
  });
 });

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