1
<div id="myDiv">
    <input type="checkbox" id="chkAgreement" value="Y" />
</div>

When do a $("#myDiv").html() or inspect the chkAgreement element in the browser, the markup doesn't get updated. I was expecting a checked attribute.

I need to grab the HTML and save it in the database. But I was surprised that the checkbox is not checked, even when it is - $("#chkAgreement").is(":checked") returns true.

What can I do to update the DOM with the proper checked attribute for the checkbox?

Should I be doing a $("#chkAgreement").attr("checked", "checked"), upon the user checking the box? It works, but is this the right approach or am I missing something?

jsadev.net
  • 2,800
  • 1
  • 16
  • 28
Zesty
  • 2,922
  • 9
  • 38
  • 69
  • 2
    I guess this is what you're looking for: [Attributes vs Properties](https://stackoverflow.com/a/6004028/3115653). Once rendered, the info whether the checkbox is checked or not is available as a property. And on toggle the property value changes, but the DOM doesn't. – a_nain Sep 16 '19 at 09:35

2 Answers2

-1

Maybe this can work (if you already have jQuery):

<script type="text/javascript">
$(document).ready(function(){
    $("#chkAgreement").change(function() { 
        if($(this).is(":checked")) { 
            //your code to update ...
        } else {
           // else statement ...
        }
    }); 
});
</script>
Hamzeen Hameem
  • 2,360
  • 1
  • 27
  • 28
P4uB0rd4
  • 175
  • 5
-1

Note:

if you're looking for a solution where you have multiple checkboxes with the same name, you checkout this demo. Also note that DOM will never change once the page is rendered unless you use some modern JS framework which would do otherwise. Therefore, we can't expect any update to the DOM based on any user interaction. @a_nain has already mentioned this.

You can do this with plain vanilla javascript:

var checkA = document.getElementById("chkAgreement");

// when the page loads
window.onload = function(e){
  console.log("checkbox value onLoad: " + checkA.checked);
}    

// when the user checks or un-checks the checkbox
checkA.addEventListener("click", () => {
  console.log('New Value:' + checkA.checked);

  if (checkA.checked) {
   console.log('Y checked');
  } else {
    console.log('Y unchecked');
  }
});
<div id="myDiv">
    <input name="agreement" type="checkbox" id="chkAgreement" value="Y"/> I agree with the terms
</div>
Hamzeen Hameem
  • 2,360
  • 1
  • 27
  • 28