abbas
abbas

Reputation: 432

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

Upvotes: 5

Views: 4456

Answers (4)

The Nail
The Nail

Reputation: 8490

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.

Upvotes: 3

graphicdivine
graphicdivine

Reputation: 11211

Try:

    document.getElementById("myChkBoxID").defaultChecked 

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

Upvotes: 4

Blender
Blender

Reputation: 298166

Just save the data when the page loads:

$(function() {
  $(':input').each(function() {
    $(this).data('default', $(this).val());
  });
});

Now, for any <input /> element, you can get its default value easily:

$('#yourInputElement').data('default');

When you want to reset the element to its default state, just call val() once more:

$('#yourInputElement').val($('#yourInputElement').data('default'));

Upvotes: 0

idrumgood
idrumgood

Reputation: 4924

You'll need to store the default value somehow. In this instance, I would think a data attribute would be acceptable.

//onload
$('#textboxID, #checkboxID').each(function(){
    $(this).data('default', $(this).val());
});

//on reset
$('#textboxID, #checkboxID').each(function(){
    $(this).val( $(this).data('default'));
});

Upvotes: 0

Related Questions