User57
User57

Reputation: 2505

Radio button filled with color

I was trying to make my radio button looks like checkbox. I have made it OK but the problem i am facing when i tried to fill it up with color. Means in default stage it's white and when i clicked it fills with black. But now i want to make it as different colors based on title and when i clicked it should filled with that color only. How do i make it ?

<label class="active">
  Email
  <span></span>
  <input type="radio" name="n1" value="email" checked>
</label>

<label>
  Phone
  <span></span>
  <input type="radio" name="n1" value="phone">
</label>

<label>
  Address
  <span></span>
  <input type="radio" name="n1" value="address">
</label>

Fiddle

Upvotes: 0

Views: 1462

Answers (2)

Prateik Darji
Prateik Darji

Reputation: 2317

You can add data-title to your label and give color to that and i have made a new style element which will change your style attribute of the radio button.

please check the below code

$(document).ready(function() {
    $('label').click(function() {
        var title = $(this).data('title');
        $('.active').removeClass("active");
        $(this).addClass("active");
        $("<style> label.active span:after{ background-color: "+title+";} </style>").appendTo("head");
    });
    $('input:checked').trigger('click');
});
label {
    width: 125px;
    display: block;
    float: left;
}

label input {
    display: none;
}

label span {
    display: block;
    width: 17px;
    height: 17px;
    border: 1px solid black;
    float: left;
    margin: 0 5px 0 0;
    position: relative;
}

label.active span:after {
    content: "";
    position: absolute;
    left: 3px;
    right: 3px;
    top: 3px;
    bottom: 3px;
    background: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<label class="active" data-title='red'>
    Email
    <span></span>
    <input type="radio" name="n1" value="email" checked>
</label>
<label data-title='green'>
    Phone
    <span></span>
    <input type="radio" name="n1" value="phone">
</label>
<label data-title='blue'>
    Address
    <span></span>
    <input type="radio" name="n1" value="address">
</label>
<label data-title='orange'>
    Address2
    <span></span>
    <input type="radio" name="n1" value="address">
</label>
<label data-title='#ff11dd'>
    Using Color Code
    <span></span>
    <input type="radio" name="n1" value="address">
</label>

Upvotes: 1

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

Having different colors based on a title (or a value)... I don't think it is possible with just CSS.

In revenge, since you exactly know their order, you can set different colors using nth-child(n).

Try:

label:nth-child(1).active span:after {
  background: red;
}
label:nth-child(2).active span:after {
  background: orange;
}
label:nth-child(3).active span:after {
  background: green;
}

Updated Fiddle

Upvotes: 0

Related Questions