我有一个表单输入,其中包含两个单选按钮,一个名字,如下所示:
<label for="thumb">[thumb]</label>
<input type="radio" name="type" value="thumb" checked />
<label for="img">[img]</label><input type="radio" name="type" value="img" />
在jQuery函数中,我引用了被选中的那个:
type=$('input[name="type"]').is(':checked').val();
由于某些原因,即使我更改了页面上的复选框,也总是返回前者。
这是完整的代码,以消除它们:
<html>
<head>
<title>Thumb/img BBCode generator</title>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<meta http-equiv="Content-Style-Type" content="text/css" />
<link href="style.css" rel="stylesheet" type="text/css" />
<noscript>Please enable Javascript or use the <a href='index2.php'>old generator</a></noscript>
</head>
<body>
<h2>Thumb/img BBCode generator for Facepunch</h2>
<div id="content">
<form id="f" action="generate2.php" method="POST">
<label for="thumb">[thumb]</label>
<input type="radio" name="type" value="thumb" checked />
<label for="img">[img]</label><input type="radio" name="type" value="img" /><br />
<textarea rows="30" cols="40" name="text">Insert image links on seperate lines</textarea><br />
<input type="button" value="Generate!" id="1_c"/>
</form>
</div>
<script>
$('#1_c').click(function(){
var text=$('textarea').val(),
type=$('input[name="type"]').is(':checked').val();
$.post('generate2.php', { text: text, type: type },
function(data) {
$("#content").html(data);
});
});
function reset(){
history.go('0');
}
</script>
</body>
实时版本:http://pdo.elementfx.com/thumb/
最佳答案
您遇到的问题是is
选择器返回布尔值,而不是匹配的元素。这意味着您最终会在val()
而不是单选按钮上调用true / false
。
尝试使用以下选择器
type=$('input[name="type"]:checked').val()
小提琴:http://jsfiddle.net/fP2P4/1/
关于jquery - jQuery返回错误的选定单选框?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7917677/