Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the value of a check box onClick using JQuery?

Here I am trying to change the value of the following check box while clicking on it. In the code below I tried to change the value of the checkbox to 1 and change the value to 0 when unchecked. But it takes only the false condition, when the checkbox is unchecked the value changes to 0 but when checked its not changing to 1. Any suggestions how to fix this out ?

<input type="checkbox" id="read" name="permission[]" onClick="($(this).checked)?$(this).attr('value',1):$(this).attr('value',0)"/>
like image 962
Bala Avatar asked Feb 04 '12 11:02

Bala


People also ask

Can we use OnClick for checkbox?

The CheckBox has been assigned a JavaScript OnClick event handler. When the CheckBox is clicked, the ShowHideDiv JavaScript function is executed. Inside this function, based on whether CheckBox is checked (selected) or unchecked (unselected), the HTML DIV with TextBox is shown or hidden.

Can we give value to checkbox?

Note: Unlike other input controls, a checkbox's value is only included in the submitted data if the checkbox is currently checked . If it is, then the value of the checkbox's value attribute is reported as the input's value.

Is checked in jQuery for checkbox?

prop() and is() method are the two way by which we can check whether a checkbox is checked in jQuery or not. prop(): This method provides an simple way to track down the status of checkboxes. It works well in every condition because every checkbox has checked property which specifies its checked or unchecked status.


1 Answers

I don't really understand why you would want to do this (the checkbox's value won't be submitted anyways when it's unchecked).

The checked property on the DOM element will always tell you whether it is checked or not. So you can either get this.checked (Javascript DOM) or $(this).prop('checked') (jQuery wrapper).

If you really need to, you should do this:

onclick="$(this).attr('value', this.checked ? 1 : 0)"

or even

onclick="$(this).val(this.checked ? 1 : 0)"

or even better, don't use inline event handlers (like onclick), but use jQuery's event handling wrappers (.on('click') or .click() in older versions).

jsFiddle Demo with jQuery event handling


The problem with your approach

You are using $(this).checked to get the state of your checkbox. The jQuery object (the one that's returned by the $ function) does not have a checked property, so it will be undefined. In Javascript, undefined is a falsy value, that's why your checkbox's value is always 0.

like image 143
kapa Avatar answered Oct 23 '22 15:10

kapa