[javascript] perform an action on checkbox checked or unchecked event on html form

I have a checkbox on a form which is unchecked by default as usual. now I want to perform two separated actions on checked and unchecked state of this checkbox.

this is my checkbox:

<form>
    syn<input type="checkbox" name="checkfield" id="g01-01"  onchange="doalert(this.id)"/>
</form>

and this is my script:

function doalert(id){
  if(this.checked) {
     alert('checked');
  }else{
     alert('unchecked');
  }
}

it just alerts uncheched!! what is the best way to do that.

This question is related to javascript html checkbox

The answer is


The currently accepted answer doesn't always work.

(To read about the problem and circumstances, read this: Defined function is "Not defined".)

So, you have 3 options:

1 (it has above-mentioned drawback)

<input type="checkbox" onchange="doAlert(this)">

<script>
function doAlert(checkboxElem) {
    if (checkboxElem.checked) {
        alert ('hi');
    } else {
        alert ('bye');
    }
}
</script>

2 and 3

<input type="checkbox" id="foo">

<script>
function doAlert() {
    var input = document.querySelector('#foo');

    // input.addEventListener('change', function() { ... });
    // or
    // input.onchange = function() { ... };
    input.addEventListener('change', function() {
        if (input.checked) {
            alert ('hi');
        } else {
            alert ('bye');
        }
    });
}

doAlert();
</script>

<form>
    syn<input type="checkbox" name="checkfield" id="g01-01" />
</form>

js:

$('#g01-01').on('change',function(){
    var _val = $(this).is(':checked') ? 'checked' : 'unchecked';
    alert(_val);
});

Given you use JQuery, you can do something like below :

HTML

<form id="myform">
    syn<input type="checkbox" name="checkfield" id="g01-01"  onclick="doalert()"/>
</form>

JS

function doalert() {
  if ($("#g01-01").is(":checked")) {
    alert ("hi");
  } else {
    alert ("bye");
  }
}

Have you tried using the JQuery change event?

$("#g01-01").change(function() {
    if(this.checked) {
        //Do stuff
    }
});

Then you can also remove onchange="doalert(this.id)" from your checkbox :)

Edit:

I don't know if you are using JQuery, but if you're not yet using it, you will need to put the following script in your page so you can use it:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

The problem is how you've attached the listener:

<input type="checkbox" ...  onchange="doalert(this.id)">

Inline listeners are effectively wrapped in a function which is called with the element as this. That function then calls the doalert function, but doesn't set its this so it will default to the global object (window in a browser).

Since the window object doesn't have a checked property, this.checked always resolves to false.

If you want this within doalert to be the element, attach the listener using addEventListener:

window.onload = function() {
  var input = document.querySelector('#g01-01');
  if (input) {   
    input.addEventListener('change', doalert, false);
  }
}

Or if you wish to use an inline listener:

<input type="checkbox" ...  onchange="doalert.call(this, this.id)">

If you debug your code using developer tools, you will notice that this refers to the window object and not the input control. Consider using the passed in id to retrieve the input and check for checked value.

function doalert(id){
  if(document.getElementById(id).checked) {
    alert('checked');
  }else{
    alert('unchecked');
  }
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to checkbox

Setting default checkbox value in Objective-C? Checkbox angular material checked by default Customize Bootstrap checkboxes Angular ReactiveForms: Producing an array of checkbox values? JQuery: if div is visible Angular 2 Checkbox Two Way Data Binding Launch an event when checking a checkbox in Angular2 Checkbox value true/false Angular 2: Get Values of Multiple Checked Checkboxes How to change the background color on a input checkbox with css?