开发者

Change on the fly the class of an html select element

The title plus the example following are clear enough (at least I hope so ;-) )

<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>
开发者_如何学JAVA


jquery:

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


No framework answer:

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


Using jQuery this can be straight-forward: http://jsfiddle.net/LfeHr/.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜