3

I have a webform with contenteditable elements and checkboxes, which on submission returns the innerHTML of the surrounding div (nothing I can change about this). For obvious reasons, this means that changes of the contenteditable elements are submitted, whereas changes of the checkbox-states are not, because as DOM properties, they are not part of the HTML attributes.

I've found a relatively simple workaround, which is to append a click-event to the elements surrounding the checkboxes and modifying the innerHTML.

Like so: http://jsfiddle.net/9Lkoaq3y/

$( ".checkboxes" ).click(function() {
  if (this.firstChild.checked) this.innerHTML=this.innerHTML.split("input").join("input checked=\"checked\"");
  else this.innerHTML=this.innerHTML.split("checked=\"checked\" ").join("");
});

I was wondering, however, whether there was a more failsafe, elegant and general way to approach this, which would also work on other form elements. In short, I don't like my ugly hack.

A related question has been asked here: innerHTML not being updated after changing value of input (checked = true/false/"checked") but without an elegant solution.

1 Answer 1

2

The easiest solution I could find (just to end this unanswered question), was to write the checked property into the checked-attribute of all checkboxes and radiobuttons everytime one of them changes a value.

This brief jquery-code takes care of this, and makes sure only those input-elements have their attribute changed where the property and the attribute do not yet correspond.

$("input[type=checkbox], input[type=radio]").change(function () {
     $("input[checked='checked']:not(:checked)").each(function (index) {
         $(this).removeAttr('checked');
     });
     $("input:not([checked='checked']):checked").each(function (index) {
         $(this).attr('checked', 'true');
     });
});
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.