views:

85

answers:

2

When an html page is loaded, different input elements can be initialed as they are declared in the HTML. If the user changes some of the input values and then executes a reset() on the form, then the form is reset to it's initial loaded state.

My question is, can I determine that "initial element state was" using javascript (ideally in a cross browser way?)

Ideally like this (where ???? is what I don't know how to do.)

<input type='checkbox' id='chkbox' checked />

<script>
alert('The initial state was ' ???? );
$('chkbox').checked = true
alert('The initial state was ' ???? );
</script>

This script would say the initial state was 'false' twice.

+1  A: 

radio- and checkbox-type inputs have a property defaultChecked defined by the W3C Level 1 and Level 2 HTML DOMs. Sadly, IE only supports it in IE8; I personally don't know of a clean solution for IE7 and before (though there may be one!). You may have to do something like the following:

// on page load:
$(':radio,:checkbox').each(function() {
    this.myDefaultChecked = this.checked;
})

You may also want to experiment with whether el.getAttribute('checked') returns the initial or current value.

Miles
A: 

Why don't you just save the state on document.ready? Pseudo-code, don't have time to test at the moment

$(document).ready(function) ({
    var checked = $('chkbox').attr("checked");
    // any other actions on the checkbox
    alert("The initial state was" + checked);
});

This way, any actions undertaken on the checkbox won't have an impact on the variable as it was saved prior to the events.

Mark Hurd