开发者

Applying and changing the classname of selected radio with scripting

开发者 https://www.devze.com 2023-04-11 15:36 出处:网络
I have a form that has a radio button set.When the page loads, I want use some simple scripting that immediately apply a classname to the label of the corresponding input and when the user click on an

I have a form that has a radio button set. When the page loads, I want use some simple scripting that immediately apply a classname to the label of the corresponding input and when the user click on another radio button in the set to remove that class and apply the classname to the newly selected radio button label.

Any ideas how this can be done?

JSFiddle: http://jsfiddle.net/eYDV4/

<form id="myForm" action="" method="post">
   <input type="radio" id="radio1" name="myRadio" value开发者_JAVA技巧="radio1">
   <label for="radio1">radio1</label>
   <input type="radio" id="radio2" name="myRadio" value="radio2">
   <label for="radio2">radio2</label>
   <input type="radio" id="radio3" name="myRadio" value="radio3" checked="checked">
   <label for="radio3">radio3</label>
   <input type="radio" id="radio4" name="myRadio" value="radio4">
   <label for="radio4">radio4</label>
</form>


You have already been given an excellent CSS-only answer, but here's an alternative using jQuery:

$(document).ready(function() {
   $("input[type='radio']:checked").next("label").addClass("newClass");
   $("input[type='radio']").click(function() {
       $("label").removeClass("newClass");
       $(this).next("label").addClass("newClass"); 
   }); 
});

If you need to support IE6, I would suggest using the jQuery method as CSS attribute selectors and adjacent sibling selectors are not supported.

Here's a working example of the above code.


It can be done with pure CSS:

input[type="radio"]:checked + label {
    color: red;
}

This selector matches label elements that are adjacent to checked radio buttons. It won't work anymore if you start adding other elements inbetween.

You can see it in action in the updated fiddle. I believe this works in all modern browsers, starting from IE7.

http://jsfiddle.net/GolezTrol/4YwLT/1/

[edit]

Hmm. The + selector works in IE7, but input:checked apparently does not. Well, it's up to you to see if you can use it. Otherwise, you can use James Allardice's answer, which uses JQuery (which about every website uses anyway).

0

精彩评论

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