Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery javascript get checkbox's initial value

I have a check box and want to get the very inital value or in other words get the default value just like we get the default value of a text box as follows:

 document.getElementById("myTextBoxID").defaultValue

I want to do the something similar either using jQuery/JS

 document.getElementById("myChkBoxID").defaultValue

So if I get a checkbox value checked from the server the very first time...now whenever the user changes the checkbox ...i should have a way of restoring it back to the very inital state

Is it possible

like image 311
abbas Avatar asked Jan 25 '12 21:01

abbas


2 Answers

Try:

    document.getElementById("myChkBoxID").defaultChecked 

https://developer.mozilla.org/en/DOM/HTMLInputElement

like image 87
graphicdivine Avatar answered Sep 28 '22 08:09

graphicdivine


Use the defaultChecked property.

defaultChecked and defaultValue are defined in DOM level 2 as follows:

defaultChecked of type boolean

When type has the value "radio" or "checkbox", this represents the HTML checked attribute of the element. The value of this attribute does not change if the state of the corresponding form control, in an interactive user agent, changes. See the checked attribute definition in HTML 4.01.

defaultValue of type DOMString

When the type attribute of the element has the value "text", "file" or "password", this represents the HTML value attribute of the element. The value of this attribute does not change if the contents of the corresponding form control, in an interactive user agent, changes. See the value attribute definition in HTML 4.01.

Note that a checkbox does have a value attribute which you can change, but it is usually not something you would want, and can cause hard-to-find bugs...

Alternatives:

Since you are letting the server set the initial value, you can include a hidden input field and let the server set the initial state on it.

Or you can reset the entire form.

like image 27
The Nail Avatar answered Sep 28 '22 06:09

The Nail