jQuery: select checkbox when upload field is clicked

Posted by Arne Stephensson on Stack Overflow See other posts from Stack Overflow or by Arne Stephensson
Published on 2010-05-15T15:42:44Z Indexed on 2010/05/15 15:44 UTC
Read the original article Hit count: 266

Filed under:
|
|
|
|

I'm working on a CMS. When a user wants to replace an existing thumbnail image, they can upload a replacement, and check a checkbox to certify that they are indeed replacing the image. The checkbox seems necessary because otherwise the form submits a blank value (due to the presence of the upload field with no value) and wipes out the existing image without a replacement image being specified.

The problem is that I keep forgetting to manually activate the checkbox and the uploaded image does not actually replace the existing one because without the checkbox being clicked, the receiving PHP file does not (by design) process the incoming filename. I suspect that users will have the same problem and I want to keep this from happening by reducing the number of steps required. One solution would be to check the checkbox with jQuery whenever the upload field is clicked. So why doesn't this work:

 $('#upload_field').click(function () {
  if ($('#replace_image').attr('checked',true)) {
   $('#replace_image').removeAttr('checked');
   alert('Unchecked');
  } else if ($('#replace_image').attr('checked',false)) {
   $('#replace_image').attr('checked','checked');
   alert('Checked');
  }
 });

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about checkbox