简体   繁体   中英

Changing color of HTML element using radio button

I have 10 groups of radio button with two options, each group separated by a <div> .

<div id = "radio1">
    <p>Do you like to walk?</p>
    <input type="radio" value="a" name="radgrp1"/> Yes <br />
    <input type="radio" value="b" name="radgrp1"/> No <br /> 
</div>

<div id = "radio2">
    <p>Would you prefer to walk without effort?</p>
    <input type="radio" value="a" name="radgrp2"/> Yes <br />
    <input type="radio" value="b" name="radgrp2"/> No <br /> 
</div>

Then I have 10 tags that point to each group.

 <a id ="a1" href="#radio1">Goto 1</a>
 <a id ="a1" href="#radio2">Goto 2</a>

What I am looking to achieve is the moment a user clicks on "Yes" option, color of respective tag ie Goto 1, Goto 2 etc turns green.

A common technique is to create a relationship between elements by using data attributes. In your case, you could put an attribute on each input/radio button that references the id of the element you want to affect.

<input type="radio" value="a" name="radgrp1" data-target="a1" /> Yes <br />

Then using some jQuery you could do this:

$('input[type="radio"]').change(function(){
    var id = $(this).attr('data-target');
    $('#' + id).css('background-color', 'rgb(255, 255, 255)');
});

You may try this (assumed there is no document.body.onclick event handler other than this)

var radios = document.querySelectorAll('input[name^=radgrp]');
document.body.onclick = function(e){
    var evt = e || window.event, target = evt.target || evt.srcElement;
    if(target.name) {
        var prefix = target.name.substr(0, 6), suffix = target.name.substr(6);
        if(prefix && prefix == 'radgrp') {
            if(target.value == 'a' ) {
                document.getElementById('a' + suffix).style.color = 'green';
            }
            else {
                document.getElementById('a' + suffix).style.color = '';
            }
        }
    }
};

Put this code just before the closing </body> tag between <script> tags like

<script type='text/javascript'> // code goes here </script>

Also, you may check this for registering events using different approaches.

Update :

querySelectorAll won't work in IE-6 so you may try this alternative solution for IE-6 to work. Also, if you use jQuery (put the code in <head> between <script> ), you may use this example and in case of jQuery , you have to add jQuery script in your <head> section section first.

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