0

So I am having some strange functionality with this snippet of jQuery:

$(document).ready(function()
{
    $('.pinToggles').attr('checked','checked');
})

This is the html:

<input type="checkbox" id="redCheck" name="pinSet" value="Red" class="pinToggles" onclick="pinSetCheck(redSet)">Red
<input type="checkbox" id="yellowCheck" name="pinSet" value="Yellow"  class="pinToggles" onclick="pinSetCheck(yellowSet)">Yellow<br>
<input type="checkbox" id="greenCheck" name="pinSet" value="Green"  class="pinToggles" onclick="pinSetCheck(greenSet)">Green
<input type="checkbox" id="blueCheck" name="pinSet" value="Blue"  class="pinToggles"onclick="pinSetCheck(blueSet)">Blue<br>

What ends up happening is if I would uncheck some of the boxes and then reload, it will only check the first unchecked box and then each refresh after that it checks the following unchecked box. The functionality that I want is on refresh is all of the checkboxes to be checked.

I was able to achieve this with javascript by using this:

document.getElementById('redCheck').checked = true;
document.getElementById('yellowCheck').checked = true;
document.getElementById('greenCheck').checked = true;
document.getElementById('blueCheck').checked = true;

But I think jQuery is the better way about doing this but unsure why it is reacting the way it is right now.

Fogolicious
  • 412
  • 8
  • 22

1 Answers1

4

use

$('input:checkbox[name="pinSet"]').prop('checked',true);

attribute-equals-selector

or

$('.pinToggles').prop('checked',true);

or

$('#redCheck,#yellowCheck,#greenCheck,#blueCheck').prop('checked',true);

.prop()

$( elem ).prop( "checked" ) true (Boolean) Will change with checkbox state

$( elem ).attr( "checked" ) (1.6) "checked" (String) Initial state of the checkbox; does not change

Community
  • 1
  • 1
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107