jQuery单选按钮显示不同的依赖项

时间:2012-12-14 21:32:20

标签: php javascript jquery html ajax

我想用jQuery做的是让我可以在同一组中使用三个单选按钮。选择一个时,其他两个不应该是活动的。我希望能够在最终结果中使用jQuery显示单独的HTML块,但是我无法使用我正在使用的内容轻松运行。

以下是我目前需要处理的代码:

    $(document.ready(function()
{
    $("input[name='rdiobut']").change(function(){
        if ($("input['rdiobut']:checked".val() == 'a'))
        $("#rdiocont").text("There is no expiration date.");
        else if ($("input[name='rdiobut']:checked".val() == 'b'))
        $("#rdiocont").text("Tell me how many days until expire");
        else ($("input[name='rdiobut']:checked".val() == 'c'))
        $("#rdiocont").text("Pick the date to expire from a calendar");
    });
});

以下是jQuery的表格:

<tr><td>Expire Settings:</td><td>Does Not Expire: <input type="radio" name="rdiobut" value="a" checked="check" /> &nbsp;&nbsp;&nbsp;<strong>OR</strong> Expires By Days <input type="radio" name="rdiobut" value="b" /> &nbsp;&nbsp;&nbsp;<strong>OR</strong> Select a Date to Expire On <input type="radio" name="rdiobut" value="c" /></td></tr><tr id="rdiocont"><td>No Expiration Date</td></tr><tr id="rdiocont"><td>Expires by Days</td></tr><tr id="rdiocont"><td>Choose Expiration by Calendar</td></tr>

有没有人对我可能做错了什么有任何建议或想法?

2 个答案:

答案 0 :(得分:1)

好的,你的代码中有一些错误。在这里你有它,所有清理和工作就像我认为你想要它(working example):

的jQuery

$(document).ready(function()
{
    $("input[name='rdiobut']").change(function(){
        if ($("input[name='rdiobut']:checked").val() == 'a')
            $("#rdiocont").text("There is no expiration date.");
        else if ($("input[name='rdiobut']:checked").val() == 'b')
            $("#rdiocont").text("Tell me how many days until expire");
        else if ($("input[name='rdiobut']:checked").val() == 'c')
            $("#rdiocont").text("Pick the date to expire from a calendar");
    });
});

HTML

<table>
    <tr>
        <td>Expire Settings:</td>

        <td>
            Does Not Expire: 
            <input type="radio" name="rdiobut" value="a" checked="checked" /> &nbsp;&nbsp;&nbsp;
            <strong>OR</strong> 
            Expires By Days 
            <input type="radio" name="rdiobut" value="b" /> &nbsp;&nbsp;&nbsp;
            <strong>OR</strong> 
            Select a Date to Expire On 
            <input type="radio" name="rdiobut" value="c" />
        </td>
    </tr>

    <tr id="rdiocont">
        <td>(Select an option)</td>
    </tr>

</table>

一些注意事项:

  • 不要对各种元素使用相同的ID(就像您在<tr id="rdiocont">中使用的那样);
  • $(document).ready,而不是$(document.ready - 关注结束)
  • 像@Ryan所说的那样,不要在else语句中评估表达式。如果您真的想要评估表达式,请继续使用else if(不必强制使用else语句)。
  • 在您的第一次评估时,它是input[name='rdiobut']而不是input['rdiobut']。您也未在)
  • 之后关闭:checked"

答案 1 :(得分:0)

首先,你的最后一个else语句,你试图将表达式评估为if语句。

其次,这是单选按钮的默认行为,只要它们具有相同的名称即可。