JavaScript:取消选择时设置单选按钮的背景(单选按钮组)

JavaScript: Set background of radio button when deselected (group of radio buttons)

本文关键字:单选按钮 背景 设置 取消 选择 JavaScript      更新时间:2023-09-26

我正在尝试创建一个简单的交互式表单以用于触摸屏设备。表单的大部分由 5 组(约 37 组)的单选按钮组成。我为每个单选按钮都有一个标签标签,当选择(单击)时,标签的背景颜色属性将在每个标签标签中使用此 JavaScript 更改为突出显示的颜色OnClick="this.style.background='#5555ff';"

我想添加到上面的是一个 JavaScript,如果组中的选择发生变化,它将删除上述内容。 例如,用户在组 1 中选择了单选按钮 A,然后在组 1 中将其选择更改为单选按钮 B。目前,两个标签背景都将更改为定义的颜色。

HTML表单由PHP动态创建,因此单选按钮名称,ID和值将有所不同。

我试图自己完成这项任务没有成功,而且似乎也没有一个简单的OnUnClick="xxx"。我在这里搜索了一个解决方案,但没有与我匹配的问题,尽管我尝试调整现有解决方案以解决类似问题,但无济于事。

感谢您的阅读!

你来了:

.HTML

<html>
    <body>
        <div>
        <input type="radio" id="g1v1" name="g1" value="v1" checked="checked"/> <label for="g1v1">V1</label>
        </div>
        <div>
        <input type="radio" id="g1v2" name="g1" value="v2" /> <label for="g1v2">V2</label>
        </div>
        <div>
        <input type="radio" id="g1v3" name="g1" value="v3" /> <label for="g1v3">V3</label>
        </div>
        <div>
        <input type="radio" id="g1v4" name="g1" value="v4" /> <label for="g1v4">V4</label>
        </div>
    </body>
</html>

爪哇语

$(document).ready(function(){
    var selectedRadioColor = "yellow";
    var normalRadioColor = "gray";
    // For changing color while document loads
    $.each($(":radio"), function(){
        //alert( $(this).prop("id")+ $(this).prop("checked") );
        if($(this).prop("checked") == false)
        {
            $(this).parent().css("color", normalRadioColor);
        }
        else
        {
            $(this).parent().css("color", selectedRadioColor );
        }
    })
    // For updating color when user interacts with radio buttons
    $(":radio").click(function(){
        $("[name='"+$(this).prop("name")+"']").parent().css("color", normalRadioColor);
        $(this).parent().css("color", selectedRadioColor );
    })
})

这是现场演示的jsfiddle链接:http://jsfiddle.net/dharmavir/6UnDs/

假设您的单选按钮分组在这样的div 中 -

<div class="radio-group">
    <INPUT TYPE=RADIO NAME="pizzasize" VALUE="S">small<BR>
    <INPUT TYPE=RADIO NAME="pizzasize" VALUE="M">medium<BR>
    <INPUT TYPE=RADIO NAME="pizzasize" VALUE="L">large<P>
</div>

你可以在jquery中做这样的事情 -

$('input[type="radio"]').click(function(){
    var parentElement = $(this).parent();
    parentElement.find('input').css('background', '#000000'); //set to your neutral background for radio buttons
    $(this).css('background', '5555ff');
});