2011-07-25 25 views
0

標題加上下面的例子是很清楚的(至少我希望如此;-))變化對飛類的HTML選擇元素

<label>Girlfriend ? :</label> 
    <input type="radio" name="girlfriend" value="yes" onclick="add required class to make the choice of an option in the select element girlfriend compulsory">Yes 
    <input type="radio" name="girlfriend" value="no" checked="checked">No 

<select name="girlfriend" id="girlfriend"> 
    <!-- Above I'd like to have class="validate['required']" if the user has chosen the radio button yes--> 
    <option value="American Girlfriend" selected="selected">American Girlfriend</option> 
    <option value="German Girlfriend" >German Girlfriend</option> 
    <option value="French Girlfriend" >French Girlfriend</option> 
</select> 
+0

是您的類叫做'驗證[ '需要']'?我不確定這是否是有效的CSS。 – pimvdb

+0

你想使用$ .validate插件嗎? – naveen

+0

@pimvdb是的,到目前爲止它的工作。 – Bruno

回答

1

的jQuery:

$('#yes_radio_button').click(function() 
{ 
$('#girlfriend').addClass("validate['required']") 
}); 
+0

雖然您需要將一個函數傳遞給'.click'。 – pimvdb

+0

@Boland感謝您的回答,但我不知道如何使用Jquery:我在哪裏放置代碼? – Bruno

+0

將其更改爲功能! – Boland

0

使用jQuery這可以是直截了當的:http://jsfiddle.net/LfeHr/

$("input:radio[name=girlfriend]").click(function() { 
    var checkedValue = $("input:radio:checked[name=girlfriend]").val(); 
    $("#girlfriend").toggleClass("validate['required']", checkedValue === "yes"); 
}); 
1

無框架答案:

var element = document.getElementsByName("girlfriend")[0]; 
if(element) 
    element.onclick = function(e){ 
    var girlfriend = document.getElementById("girlfriend"); 
    if(girlfriend) 
     girlfriend.className += " validate['required']"; 
    }