julianc julianc - 6 months ago 18
HTML Question

showing Confirm message when unchecking a checkbox in javascript

I want a message that reads "are you sure?" to display when the user tries to uncheck a checkbox. If they choose something like "yes", then uncheck it. If they choose "no", then leave as is. I'm fairly new to JavaScript and my attempt at this has prompted me with the error "JavaScript runtime error: Unable to get property 'checked' of undefined or null reference". Here is my Checkbox code:

<div id="ChkBox">
<input style="margin: 5px; " type="checkbox" name="chkIsActive" onchange="Areyousure('ChkBox')" value="@Model.Pharmacy.IsActive" @(Model.Pharmacy.IsActive =="True" ? "checked=\"checked\"" : "") /> Is Active
</div>
<script>
Areyousure();
</script>


and here is the function:

function Areyousure(id) {
if (document.getElementById(id).checked == true) {
return false;
} else {
var box = confirm("Are you sure you want to Uncheck this?");
if (box == true)
return true;
else
document.getElementById(id).checked = true;
}
}


What can i do to fix this? Thanks in Advance!

Answer

You could consider passing in the element itself to avoid any issues with targeting it based on its id attribute using :

onchange='Areyousure(this);'

And then adjust your function accordingly to handle determine if the checked attribute should persist through the change or not :

function Areyousure(element) {
    // If it is checked now, let it be
    if (element.checked) {
        return false;
    // Otherwise prompt the user
    } else {
        // Prompt the user to make sure
        if (confirm("Are you sure you want to Uncheck this?")){
            // The user confirmed it, so uncheck it
            return true;
        }else{
            // Otherwise, keep it checked
            element.checked = true;
        } 
    }
}

Example

enter image description here

<div id="ChkBox">
  <input style="margin: 5px; " type="checkbox" name="chkIsActive" onchange="Areyousure(this)" value="example" checked />Is Active
</div>
<script>
  function Areyousure(element) {
    // If it is checked now, let it be
    if (element.checked) {
        return false;
    // Otherwise prompt the user
    } else {
        // Prompt the user to make sure
        if (confirm("Are you sure you want to Uncheck this?")){
            // The user confirmed it, so uncheck it
            return true;
        }else{
            // Otherwise, keep it checked
            element.checked = true;
        } 
    }
}
</script>