John Higgins John Higgins - 2 months ago 16
Javascript Question

Clear form using a checkbox

I am trying to use a checkbox to clear a form but I do not want the reset to clear the checkbox itself. The code I am using is as follows:

<input name="no_cage" id="no_cage" type="checkbox" value="1" onclick="this.form.reset();">


When I click on the checkbox it clears the form fine but unfortunately, also clear itself too.

The checkbox also updates a db with a 1 if checked or a 0 if unchecked. So I need it within the form and it needs to be able to toggle between checked and unchecked.

Answer

There are two ways to do this:

Create a javascript function to reset the form and then check the checkbox again to true.

Using JQuery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).on('change', '#no_cage', function() {
    if(this.checked) {
        document.getElementById("client").reset();
        this.checked = true;
    }
});
</script>
<form id="client">
    <input type="text">
    <input id="no_cage" type="checkbox" value="1"> CLEAR
</form>

Using Javascript:

<script type="text/javascript">
function clearform(){
    if (document.getElementById("no_cage").checked == true){
        document.getElementById("client").reset();
        document.getElementById("no_cage").checked = true;
    }
}
</script>
<form id="client">
    <input type="text">
    <input id="no_cage" type="checkbox" onclick="javascript:clearform();"> CLEAR
</form>

OR, keep the checkbox out of the form

<script type="text/javascript">
function clearform(){
    document.getElementById("client").reset();
}
</script>
<form id="client">
    <input type="text">
</form>
<input id="no_cage" type="checkbox" value="1" onclick="javascript:clearform();"> CLEAR