动态更改html选择元素的类

时间:2011-07-25 09:33:07

标签: javascript html select

标题加上以下示例足够清楚(至少我希望如此;-))

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

3 个答案:

答案 0 :(得分:1)

jquery的:

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

答案 1 :(得分:1)

没有框架答案:

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

答案 2 :(得分: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");
});