Getting Value of HTML Checkbox from Onclick/Onchange Events

Getting value of HTML Checkbox from onclick/onchange events

The short answer:

Use the click event, which won't fire until after the value has been updated, and fires when you want it to:

<label><input type='checkbox' onclick='handleClick(this);'>Checkbox</label>

function handleClick(cb) {
display("Clicked, new value = " + cb.checked);
}

Live example | Source

The longer answer:

The change event handler isn't called until the checked state has been updated (live example | source), but because (as Tim Büthe points out in the comments) IE doesn't fire the change event until the checkbox loses focus, you don't get the notification proactively. Worse, with IE if you click a label for the checkbox (rather than the checkbox itself) to update it, you can get the impression that you're getting the old value (try it with IE here by clicking the label: live example | source). This is because if the checkbox has focus, clicking the label takes the focus away from it, firing the change event with the old value, and then the click happens setting the new value and setting focus back on the checkbox. Very confusing.

But you can avoid all of that unpleasantness if you use click instead.

I've used DOM0 handlers (onxyz attributes) because that's what you asked about, but for the record, I would generally recommend hooking up handlers in code (DOM2's addEventListener, or attachEvent in older versions of IE) rather than using onxyz attributes. That lets you attach multiple handlers to the same element and lets you avoid making all of your handlers global functions.


An earlier version of this answer used this code for handleClick:

function handleClick(cb) {
setTimeout(function() {
display("Clicked, new value = " + cb.checked);
}, 0);
}

The goal seemed to be to allow the click to complete before looking at the value. As far as I'm aware, there's no reason to do that, and I have no idea why I did. The value is changed before the click handler is called. In fact, the spec is quite clear about that. The version without setTimeout works perfectly well in every browser I've tried (even IE6). I can only assume I was thinking about some other platform where the change isn't done until after the event. In any case, no reason to do that with HTML checkboxes.

Javascript checkbox onChange

function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}

HTML

<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>

Javascript Html.Checkbox onchange event

You can get checkbox as a element in your function by passing this as a reference see updated markup below

<input type="checkbox" value="check" id="AutoCalculateMandate" onchange = "AutoCalculateMandateOnChange(this)"/>
<label for="AutoCalculateMandate">
Auto Calculate
</label> <br />

Since you're using MVC so it can be achieved like this:

 @Html.CheckBox("AutoCalculateMandate", true , new { onchange = "AutoCalculateMandateOnChange(this)" })

javascript

function AutoCalculateMandateOnChange(element){
document.getElementById("LevyFee").disabled = element.checked;
}

Demo

Is it possible assign the checked state to the value of the current checkbox in razor form without onclick method?

Yes you can do it by using an inline razor statement @()
It would look something like this:

<input type="checkbox" id="IsActive" name="DTO.IsActive" @(Model.IsActive ? "checked" : "") />

also you could use the Checkbox helper

@Html.CheckBoxFor(model => model.IsActive )

How do you create onchange event for checkbox in javascript?

I changed my code to this and it works.

function createTable(channelArr, id) {
console.log(channelArr)
var table = document.getElementById("channelsTable");
for (i = 0; i < channelArr.length; i++) {
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
let inverseIndex = channelArr.length - 1 - i
cell1.innerHTML = "# " + channelArr[inverseIndex].name
var checkbox = document.createElement("INPUT");
checkbox.type = "checkbox";
checkbox.onchange = () => checkClicked(inverseIndex);
if (channelArr[i].members.indexOf(id) != -1) {
checkbox.checked = true
}
cell2.appendChild(checkbox)
}
}

Click vs Input vs Change for checkboxes?

These 3 events duplicate each other's functionality because you are looking at a checkbox which happens to be a special case.

For example, if you were to take a text field

  • The event input will fire whenever the text in an element is changed using the user interface.
  • The event change will fire (on most browsers) whenever the text element loses focus. It would only be triggered once instead of after every keystroke.
  • The event click will fire whenever a user clicks on the text field.

If we were to apply this to checkboxes (keeping in mind there is only one thing a checkbox can be changes into: either checked => unchecked orunchecked => checked)

  • The event input will fire whenever the checked state is changed using user interface.
  • The event change will fire whenever the checked state has changed
    in an element (or when the checkbox loses focus in IE).
  • The event click will fire after the check state has finished changing .

The 3 events have very similar functionality (almost duplicates) because they are all trying to do something different that functionally does the same thing on checkboxes. The only differences being subtle implementation details.

I would use click to avoid having issues from the user of diffrent browsers.

How to read a checkbox's @onclick event after the value

Assuming that the Mud CheckBox is successfully binding to the boolean, then you could use a custom get; set; for it. However, be careful what you do with that-- you probably don't want to call an involved async Task with it.

<input type="checkbox" @bind="CheckTest"/>
@Message

@code {
string Message;

private bool _checkTest;
bool CheckTest
{
get { return _checkTest; }
set { _checkTest = value; HandleCheck(value); }
}

void HandleCheck(bool IsChecked)
{
Message = IsChecked ? "Do something" : "Don't do the thing";
}
}

I find it a little hard to believe, though, that the Mud Checkbox wouldn't correctly handle @onchange.



Related Topics



Leave a reply



Submit