senty senty - 4 months ago 30
jQuery Question

Materializecss - prop radio checkbox with jQuery on click

I have 1 radio item, and I want it to behave like a checkbox. So now, it gets selected but I couldn't bind it to prop state on click.

So I want to achieve is: when clicked on radio btn, it reverses its checked state.

Here is what I tried:

<form action="#">
<p>
<input name="group" type="radio" id="test" />
<label for="test">Red</label>
</p>
</form>


$(document).ready(function() {
$('#test').click(function() {
$('#test').prop('checked', !$('#test').prop('checked'))
})
})


What interesting is, if I create another button and bind it to change
checked
value, it works

<button id="faker" type="button">
Faker Btn
</button>

$('#faker').click(function() {
$('#test').prop('checked', !$('#test').prop('checked'))
})


Here is a fiddle: https://jsfiddle.net/55L52yww/81/

Answer Source

A radio can behave like a checkbox if you add a state attribute to the radio element like in:

<input name="group" type="radio" id="test" data-state="false"/>

Now, you can save the last state and compare with the current value in order to decide the action to do.

The snippet:

$('#test').on('click', function(e) {
  var a = $(this).data('state');
  var b = $(this).prop('checked');
  if (a && b) {
      b = false;
      $(this).prop('checked', b);
  }
  $(this).data('state', b);
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>


<form action="#">
    <p>
        <input name="group" type="radio" id="test" data-state="false"/>
        <label for="test">Red</label>
    </p>
</form>