0

I have a specific problem where I need to render a html string from the server and show it to the user. The user then clicks the checkboxes and I transform it back into a html string and save it on the server.

Problem is after the user clicks the checkboxes, the transformed HTML string does not contain the checked attribute.

Here is a snippet

$("button").on("click", function(){

   console.log($("#container").html());

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
    <input type="checkbox" id="checkbox"/>
    <button> Test </button>
</div>

But when I manually click the checkbox and click the button and examine the console log, the checked attribute inside the HTML string is not seen.

How can I solve this problem?

2 Answers 2

2

Set checked attribute manually by .attr('checked', 'checked') on change:

$("button").on("click", function() {

  console.log($("#container").html());

});

$('#checkbox').change(function() {
  if ($(this).is(':checked')) {
    $(this).attr('checked', 'checked');
  } else {
    $(this).removeAttr('checked');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <input type="checkbox" id="checkbox" />
  <button> Test </button>
</div>

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

Comments

1

When you check a checkbox manually, the checked HTML attribute doesn't change.

You can change it yourself by selecting every checked checkbox and manually updating them with the jQuery :checked selector:

$('#container input[type="checkbox"]:checked').attr('checked','true');

$("button").on("click", function() {
  $('#container input[type="checkbox"]:checked').attr('checked','true');
  console.log($("#container").html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <input type="checkbox" id="checkbox" />
  <button> Test </button>
</div>

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.