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
4
  • Is the form re-initiated (re-rendered) each time the user opens the modal window? Are you saving the checkbox's state somehow? Commented Feb 7, 2016 at 12:34
  • 2
    It looks like you're using .attr as if it were .prop Commented Feb 7, 2016 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. Commented Feb 7, 2016 at 12:41
  • Please provide enough of your code (see the "minimal reproducible example" guidelines) to allow us to reproduce your issue, and the context of your ur question/problem. Commented Feb 7, 2016 at 12:41

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.