简体   繁体   中英

Adding css to radio button for checked and clear css unchecked in js

How do I style the radio button for checked only and clear it? I've tried several ways. It's not clearing.

$('input:radio').on('click', function () {
    var $field_type = $("[name=field]:checked");
    #and other field types doing the same thing
    $("label[for='" + $field_type.attr('id') + "']").css({'border': '2px solid #333'})

I also tried $("label[for='" + $(this).attr('id') + "']").css({'border': '2px solid #333'}) . It does the same thing.

 $('input:radio').on('click', function () { $('input[name="RD"]').next().css({'border': 'none'}); $("label[for='" + $(this).attr('id') + "']").css({'border': '2px solid #333'}) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="radio" name="RD" id="RD1"/><label for="RD1">radio1</label> <br> <input type="radio" name="RD" id="RD2"/><label for="RD2">radio2</label> 

The best approach is to simply write a CSS selector that kicks in when the radio button is checked. No JavaScript needed.

But keep in mind that not all browsers allow radio buttons to be styled in any way you like. However, the label elements that go with them can be styled easily:

 /* This rule will only be appled when the radio button is selected. but, not all browsers allow radio button styling. */ input[type='radio']:checked { background-color:yellow; } /* This rule will affect the label that comes after the checked radio button: */ input[type='radio']:checked + label { border:1px solid red; } 
 <input type="radio" name="test" id="test" value="on"><label for="test">On</label> <input type="radio" name="test" id="test2" value="off"><label for="test2">Off</label> 

Here's an interesting link that shows how to customize the buttons and check marks easily.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM