jQuery返回错误选择的radiobox? [英] jQuery returning wrong selected radiobox?

查看:91
本文介绍了jQuery返回错误选择的radiobox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两个单选按钮的表单输入,一个名称,如下所示:

I have a form input consisting of two radiobuttons, for one name, as below:

<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函数中,我引用了哪一个被检查:

Within a jQuery function I reference which one is checked as such:

type=$('input[name="type"]').is(':checked').val();

出于某种原因,即使我更改了页面上的复选框,如果总是返回前者。

For some reason, even if I have changed the checked box on the page, if always returns the former.

以下是完整代码,用于消除:

Here's the full code, for purposes of elimination:

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

推荐答案

问题你'遇到的是选择器返回一个布尔值而不是匹配的元素。这意味着您最终在 true / false 上调用 val()而不是单选按钮。

The problem you're running into is the is selector returns a boolean value and not the matched element. This means you end up calling val() on true / false instead of the radio button.

尝试使用以下选择器

type=$('input[name="type"]:checked').val()

小提琴: http://jsfiddle.net/fP2P4/1/

这篇关于jQuery返回错误选择的radiobox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆