How to change input pseudo-class using javascript?

I am trying to create a switch list of styles, but I am not really using the input type = radio. My third-party developer advised me to create this using type = "checkbox" in our particular case. I believe this can be done with JS. So, how can I make it so that when 1 parameter is in check state, the other is not set using JS? Here is what I still have:

http://codepen.io/rjtkoh/pen/VLZrMo

<label for="toggle-1">
<input type="checkbox" id="toggle-1">
<div>option A</div>
  </label>

<label for="toggle-2">
<input type="checkbox" id="toggle-2">
<div>option B</div>
</label>

and CSS:

/* Checkbox Hack */

input[type=checkbox] {
   position: absolute;
   top: -9999px;
   left: -9999px;
}

/* Default State */
div {
   background: green;
   width: 400px;
   height: 100px;
   line-height: 100px;
   color: white;
   text-align: center;
   margin-bottom: 20px;
}

/* Toggled State */
input[type=checkbox]:checked ~ div {
   background: red;
}

I looked at other topics about changing pseudo classes through JS, but my input type business is confusing to me.

+4
source share
3 answers

checkbox, radio? , , , , , - JavaScript, name :

input[type=radio] {
   position: absolute;
   top: -9999px;
   left: -9999px;
}

/* Default State */
div {
   background: green;
   width: 400px;
   height: 100px;
   line-height: 100px;
   color: white;
   text-align: center;
   margin-bottom: 20px;
}

/* Toggled State */
input[type=radio]:checked + div {
   background: red;
}
<label for="toggle-1">
  <input type="radio" name="option" id="toggle-1">
  <div>option A</div>
</label>

<label for="toggle-2">
  <input type="radio" name="option" id="toggle-2">
  <div>option B</div>
</label>
Hide result
+3

javascript, jQuery :

, :

HTML

<div id="radio_group">
<label for="toggle-1">
<input type="checkbox" id="toggle-1">
<div>option A</div>
</label>

<label for="toggle-2">
<input type="checkbox" id="toggle-2">
<div>option B</div>
</label>
</div>

Javascript

var options = document.getElementById('radio_group').childNodes;
var checkboxes = document.getElementsByTagName('input');

function uncheck() {
    for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i].type == 'checkbox') {
           checkboxes[i].checked = '';
        }
    }
}

function checkBox(e) {
  e.preventDefault();
  if(e.target.nodeName == 'DIV') {
    uncheck();
    e.target.previousElementSibling.checked = 'checked';    
  }
}

for (var i = 0; i < options.length; i++) {
    options[i].addEventListener('click', checkBox, false);
}

heres a fiddle → https://jsfiddle.net/tL68Lsub/

+1

If you really need a checkbox to work as a radio, you can use:

$("input[type='checkbox']").click(function () {
    if ($(this).is(":checked")) {
        $("input[type='checkbox']").not(this).removeAttr("checked");
        $(this).attr("checked", "true");
    }
})
0
source

All Articles