2014-09-12 71 views
0

當radi按鈕值爲Agent時,我想隱藏div(AppliedCourse)。我寫了下面的代碼,但它不工作。 有什麼想法?使用jquery隱藏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

嘗試=='代理',也在哪裏你的div? – Quantico 2014-09-12 17:02:51

+2

$('#HearAboutUs')的目標是一個ID爲HearAboutUs的元素。我的例子中沒有看到一個。修復Quantico指出的錯誤和它的工作原理http://jsfiddle.net/j08691/v6nnmtyx/ – j08691 2014-09-12 17:06:25

+0

還有你檢查了你的控制檯嗎?我試圖將你的代碼複製到jsfiddle,並且有一堆錯誤。由於@ j08691表示你的身份證號碼在哪裏 – Quantico 2014-09-12 17:07:09

回答

3

無論你的HTML是不完整的或你的第一選擇是錯誤的。有可能你的點擊處理程序沒有被調用,因爲你沒有元素的ID爲'HeadAboutUs'。在這種情況下,您可能想要聽取輸入本身的點擊。

另外,你的邏輯不太對。如果參數爲false,則切換隱藏元素,所以您想使用!=來取消它。嘗試:

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

我已經做了的jsfiddle與工作解決方案:http://jsfiddle.net/c045fn2m/2/

+0

我想你' 「HearAboutUs'附近缺少引號 – Dan 2014-09-12 17:18:13

+0

謝謝@Dan,但我並不嚴格要求他們。」屬性值必須是標識符或字符串。「來自:http://www.w3.org/TR/CSS21/selector.html#attribute - 選擇器 – 2014-09-12 17:28:53

+0

謝謝@Regent我添加了更新的鏈接 – 2014-09-12 17:32:34

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(); 
} 
}); 
+1

'$('#AppliedCourse')。toggle(value!== '代理人');'比if-else'短得多,但是以相同的方式運作 – Regent 2014-09-12 17:23:56

+0

是的,你說得對,當你試圖儘快回答問題時會發生什麼 – Sergey6116 2014-09-12 17:49:56

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語句。這也適用。

+0

爲什麼你不想使用'.toggle()'而不是'if-else'? – Regent 2014-09-12 17:26:42

+0

@Regent是啊我在另一個問題上看到了你的記錄 - 這是一件好事理念! – Dan 2014-09-12 17:30:38

相關問題