218

I have a checkbox in a form and I'd like it to work according to following scenario:

  • if someone checks it, the value of a textfield (totalCost) should be set to 10.
  • then, if I go back and uncheck it, a function calculate() sets the value of totalCost according to other parameters in the form.

So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
bikey77
  • 6,384
  • 20
  • 60
  • 86

10 Answers10

265

Pure javascript:

const checkbox = document.getElementById('myCheckbox')

checkbox.addEventListener('change', (event) => {
  if (event.currentTarget.checked) {
    alert('checked');
  } else {
    alert('not checked');
  }
})
My Checkbox: <input id="myCheckbox" type="checkbox" />
olfek
  • 3,210
  • 4
  • 33
  • 49
Vic
  • 8,261
  • 6
  • 42
  • 55
199
function calc()
{
  if (document.getElementById('xxx').checked) 
  {
      document.getElementById('totalCost').value = 10;
  } else {
      calculate();
  }
}

HTML

<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
tony gil
  • 9,424
  • 6
  • 76
  • 100
Senad Meškin
  • 13,597
  • 4
  • 37
  • 55
  • 59
    And if the user uses the keyboard? – thomthom Dec 18 '13 at 11:36
  • Can you write jsFiddle so that I can try this? I am also having to have a checkbox do stuff when clicked. – Mike Warren Jan 31 '15 at 09:58
  • 13
    [Here's a JsFiddle](http://jsfiddle.net/wv97mpcp/) where all the different ways can be tested: click, keyboard, label and accesskey. They all trigger the event in Firefox. – Roman Starkov May 08 '15 at 12:59
  • 5
    Unfortunately, the event is not triggered when the checkbox state is changed through JavaScript. – StanE Jun 23 '15 at 22:30
  • 2
    lol, use this from javascript $('#checkbox').attr('checked','checked'); $('#checkbox').click(); – Senad Meškin Jun 24 '15 at 17:11
  • I am having issue with this. onclick triggers before the state actually changes. So if I loop through to calculate a sum based on what is not clicked, the one being clicked is included. – Allen King Sep 16 '16 at 00:52
  • At least pass the id as the argument to `calc` function. This is wrong on so many levels. – notgiorgi May 31 '17 at 12:43
  • this is the question how to do something, not how to finish the project. I know what you are talking, but the answer is the solution to one problem not to every problem. – Senad Meškin May 31 '17 at 13:36
  • 17
    You should use onchange instead, it's specifically designed for the OP's use case. (thanks ReeCube below for the link) developer.mozilla.org/en-US/docs/Web/Events/change – Alicia Jan 24 '18 at 21:48
37

If you are using jQuery.. then I can suggest the following: NOTE: I made some assumption here

$('#my_checkbox').click(function(){
    if($(this).is(':checked')){
        $('input[name="totalCost"]').val(10);
    } else {
        calculate();
    }
});
DBS
  • 9,110
  • 4
  • 35
  • 53
Liangliang Zheng
  • 1,763
  • 11
  • 16
19

HTML:

<input type="checkbox" onchange="handleChange(event)">

JS:

function handleChange(e) {
     const {checked} = e.target;
}
Ali Kleit
  • 3,069
  • 2
  • 23
  • 39
19

Use an onclick event, because every click on a checkbox actually changes it.

TRiG
  • 10,148
  • 7
  • 57
  • 107
SergeS
  • 11,533
  • 3
  • 29
  • 35
17

The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.

const checkbox = $("#checkboxId");

checkbox.change(function(event) {
    var checkbox = event.target;
    if (checkbox.checked) {
        //Checkbox has been checked
    } else {
        //Checkbox has been unchecked
    }
});
Eugene
  • 473
  • 1
  • 9
  • 15
4

Reference the checkbox by it's id and not with the # Assign the function to the onclick attribute rather than using the change attribute

var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
    var checkbox = event.target;

    if (checkbox.checked) {
        //Checkbox has been checked
    } else {
        //Checkbox has been unchecked
    }
};
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Bart
  • 49
  • 1
0

Javascript

  // on toggle method
  // to check status of checkbox
  function onToggle() {
    // check if checkbox is checked
    if (document.querySelector('#my-checkbox').checked) {
      // if checked
      console.log('checked');
    } else {
      // if unchecked
      console.log('unchecked');
    }
  }

HTML

<input id="my-checkbox" type="checkbox" onclick="onToggle()">

0x1ad2
  • 8,014
  • 9
  • 35
  • 48
0

try

totalCost.value = checkbox.checked ? 10 : calculate();

function change(checkbox) {
  totalCost.value = checkbox.checked ? 10 : calculate();
}

function calculate() {
  return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
0

I know this seems like noob answer but I'm putting it here so that it can help others in the future.

Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.

<!-- Begin Loop-->
<tr>
 <td><?=$criteria?></td>
 <td><?=$indicator?></td>
 <td><?=$target?></td>
 <td>
   <div class="form-check">
    <input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>> 
<!-- mark as 'checked' if checkbox was selected on a previous save -->
   </div>
 </td>
</tr>
<!-- End of Loop -->

You place a button below the table with a hidden input:

<form method="post" action="/goalobj-review" id="goalobj">

 <!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->

 <input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
 <button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>

You can write your script like so:

<script type="text/javascript">
    var checkboxes = document.getElementsByClassName('form-check-input');
    var i;
    var tid = setInterval(function () {
        if (document.readyState !== "complete") {
            return;
        }
        clearInterval(tid);
    for(i=0;i<checkboxes.length;i++){
        checkboxes[i].addEventListener('click',checkBoxValue);
    }
    },100);

    function checkBoxValue(event) {
        var selected = document.querySelector("input[id=selected]");
        var result = 0;
        if(this.checked) {

            if(selected.value.length > 0) {
                result = selected.value + "," + this.value;
                document.querySelector("input[id=selected]").value = result;
            } else {
                result = this.value;
                document.querySelector("input[id=selected]").value = result;
            }
        }
        if(! this.checked) { 

// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.

            var compact = selected.value.split(","); // split string into array
            var index = compact.indexOf(this.value); // return index of our selected checkbox
            compact.splice(index,1); // removes 1 item at specified index
            var newValue = compact.join(",") // returns a new string
            document.querySelector("input[id=selected]").value = newValue;
        }

    }
</script>

The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.

Bruce Tong
  • 1,366
  • 15
  • 14