views:

56

answers:

2

I have a checkbox that when it is clicked it submits the form to the server to store the detail. All works fine except that after the form is submitted I update a div to say submitted but the checkbox isn't ticked. The page isn't refreshed of course and upon page refresh it is ticked.

I thought I might be able to check the box myself as I'm using jQuery but I have a lot of these checkboxes each with a dynamic name so I'm not sure how I would call them. I thought something like:

$('input[name=("favourite" + id)]').attr('checked', true);

might work but no luck. If I don't call the function on the checkbox being ticked the checkbox behaves normally.

Thanks for anything that could help.

+1  A: 

You should break your string in order to introduce the value of the id variable into your selector, you can do it like this:

$('input[name="favourite' + id + '"]').attr('checked', true);
CMS
Yup, that was it thanks. I rarely use Javascript :(
Rudiger
+1  A: 

Try doing

$('input[name=("favourite" + id)]').checked = true;

instead.

The issue may be that setting the attribute is not automatically interpreted by your browser as changing the DOM property. This is a bit confusing, but on browsers like Firefox, etc, HTML attributes and DOM properties are stored separately (most are named the same, but there are exceptions - such as the class attribute being represented by the className property).

Changing properties affects the behavior of the Elements, while attributes do not always have the same effect - on some browsers they are only parsed during initial render.

levik
Also $('input[name=("favourite" + id)]').attr('checked','checked'); might give you better results as the checked attribute is supposed to be a string. However i've the above method works more consistantly.
Josiah
Tried, didn't work :(
Rudiger