Orbitall
Orbitall

Reputation: 661

jQuery unchecking and reselecting checkbox programmatically

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

Upvotes: 0

Views: 117

Answers (1)

Orbitall
Orbitall

Reputation: 661

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()

Upvotes: 1

Related Questions