使用jquery隐藏单选按钮选择值的div-不工作

时间:2014-09-12 17:00:14

标签: javascript jquery

当单选按钮值为Agent时,我想隐藏div(应用课程)。我写下面的代码,但它不起作用。 有什么想法吗?

$('#HearAboutUs').click(function() {
    $("#AppliedCourse").toggle($('input[name=HearAboutUs]:checked').val()='Agent');
    });

 <tr><td class="text"><input type="radio" name="HearAboutUs" value="Press">Press & Print media
<input type="radio" name="HearAboutUs" value="Internet">Internet
<input type="radio" name="HearAboutUs" value="Agent">Agent
<input type="radio" name="HearAboutUs" value="Friend">Friend
<input type="radio" name="HearAboutUs" value="Other" checked="checked">Other</td></tr>

3 个答案:

答案 0 :(得分:3)

您的HTML不完整或第一个选择器错误。您的点击处理程序可能未被调用,因为您没有ID为&#39; HeadAboutUs&#39;的元素。在这种情况下,您可能希望听取输入本身的点击次数。

另外,你的逻辑并不完全正确。如果参数为false,则Toggle会隐藏元素,因此您希望使用!=来取消它。尝试:

$('input[name=HearAboutUs]').click(function() {
    var inputValue = $('input[name=HearAboutUs]:checked').val()
    $("#AppliedCourse").toggle( inputValue!='Agent');
});

我用一个有效的解决方案制作了一个JSFiddle:http://jsfiddle.net/c045fn2m/2/

答案 1 :(得分:3)

您的代码正在寻找ID为HearAboutUs的元素,但您的页面上没有这个元素。

你有name="HearAboutUs"的一堆输入。如果您寻找这些,您将能够执行您的代码。

$("input[name='HearAboutUs']").click(function() {
    var clicked = $(this).val(); //save value of the input that was clicked on
    if(clicked == 'Agent'){ //check if that val is "Agent"
        $('#AppliedCourse').hide();
    }else{
        $('#AppliedCourse').show();
    }
});

<强> JS Fiddle Demo

@Regent建议的另一个选项是用$('#AppliedCourse').toggle(clicked !== 'Agent');替换if / else语句。这也有效。

答案 2 :(得分:1)

这是小提琴:http://jsfiddle.net/L9bfddos/

<tr>
<td class="text">
     <input type="radio" name="HearAboutUs" value="Press">Press & Print media
     <input type="radio" name="HearAboutUs" value="Internet">Internet
     <input type="radio" name="HearAboutUs" value="Agent">Agent
     <input type="radio" name="HearAboutUs" value="Friend">Friend
     <input type="radio" name="HearAboutUs" value="Other" checked="checked">Other
</td>

测试
$("input[name='HearAboutUs']").click(function() {
var value = $('input[name=HearAboutUs]:checked').val();
if(value === 'Agent'){
    $('#AppliedCourse').hide();
}
else{
    $('#AppliedCourse').show();
}
});