0

I have a bootstrap modal with a form inside, This means I require to programmatically set check boxes. When I attempt to programmatically select, deselect then reselect the checkbox the reselection doesn't get made.

Whenever I call .attr('checked', false); the following .attr('checked', true) doesn't seem to make changes.

How can I check the checkbox after it been unchecked?

HTML

<input value="None" name="hazards[]" id="hazard1" type="checkbox">

jQuery

$('#hazard1').attr('checked', true); //automated input check
$('#hazard1').attr('checked', false); //User cancels form and unchecks input
$('#hazard1').attr('checked', true); //Reopens form, but doesnt get checked
Cœur
  • 37,241
  • 25
  • 195
  • 267
Orbitall
  • 611
  • 11
  • 36
  • Is the form re-initiated (re-rendered) each time the user opens the modal window? Are you saving the checkbox's state somehow? – MorKadosh Feb 07 '16 at 12:34
  • 2
    It looks like you're using `.attr` as if it were `.prop` – Stryner Feb 07 '16 at 12:34
  • @Stryner - Thanks, havnt used `.prop` much before. This solved the problem...look like ill be replacing alot of my `.attr` with this now. – Orbitall Feb 07 '16 at 12:41
  • Please provide enough of your code (see the "[mcve]" guidelines) to allow us to reproduce your issue, and the context of your ur question/problem. – David Thomas Feb 07 '16 at 12:41

1 Answers1

1

Thanks to Stryner for poinitng out this quick solution for something I have overlooked.

The solution is to simply replace the .attr() with .prop(). This is an updated syntax that replaces the .attr. Unlike the 'attribute' providing just a string, the 'property' provides more infomation on its property type allowing the use of bools (which are needed for checkboxes).

.prop() vs .attr()

Community
  • 1
  • 1
Orbitall
  • 611
  • 11
  • 36