Ben Rei
Ben Rei

Reputation: 109

How can I make the radio boxes in html look like checkboxes and make them have x's when checked?

I want to make a form that has radio boxes that look like checkboxes. Furthermore I want them to have the glyphcon x's when checked. I tried several solutions for this including:

        input[type="radio"] {
            -webkit-appearance: checkbox; /* Chrome, Safari, Opera */
            -moz-appearance: checkbox;    /* Firefox */
            -ms-appearance: checkbox;     /* not currently supported */
        }

When I used this solution it made checkboxes with line across the checkbox that would disappear after one was checked and they were hovered over.

I also tried the solutions offered here: How to style checkbox using CSS? and they did not seem to work.

Can somebody please help me?

Upvotes: 0

Views: 323

Answers (1)

NewToJS
NewToJS

Reputation: 2772

Maybe this solution would make things easier for you.

I have written this function so you can use it on as many check boxes as you want. The only requirement it to give them a class of radio and the same name for that group of options.

jQuery Solution

$('input[type=checkbox][class=radio]').on('change', function(e) {
  var Group = this.name;
  $('input[type=checkbox][name=' + Group + '][class=radio]').prop('checked', false);
  this.checked = true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>Eyes</h4>
Blue <input type="checkbox" name="eyes" class="radio"> 
Green <input type="checkbox" name="eyes" class="radio"> 
Brown <input type="checkbox" name="eyes" class="radio">
<h4>Hair</h4>
Black <input type="checkbox" name="hair" class="radio"> 
Brown <input type="checkbox" name="hair" class="radio"> 
Ginger <input type="checkbox" name="hair" class="radio">

Pure Javascript Solution

var checks = document.getElementsByClassName('radio');
for (var i = 0; i < checks.length; i++) {
  checks[i].addEventListener('change', radios, false);
}

function radios() {
  var x = document.querySelectorAll("input[name=" + this.name + "]");
  for (var i = 0; i < x.length; i++) {
    x[i].checked = false
  }
  this.checked = true;
}
<h4>Eyes</h4>
Blue <input type="checkbox" name="eyes" class="radio"> 
Green <input type="checkbox" name="eyes" class="radio"> 
Brown <input type="checkbox" name="eyes" class="radio">
<h4>Hair</h4>
Black <input type="checkbox" name="hair" class="radio"> 
Brown <input type="checkbox" name="hair" class="radio"> 
Ginger <input type="checkbox" name="hair" class="radio">

If you have any question about the source code above please leave a comment below and I will get back to you as soon as possible.

I hope this helps. Happy coding!

Upvotes: 1

Related Questions