How do I find the previous / default for a radio button in JS?

I'm not sure if this is possible, but I thought I'd ask before the club comes up with an ugly solution.

I have a group of radio buttons and I want to call a function if the value of the radio button is changed. For example, suppose there are three buttons XY and Z with the default Y selected. If the user clicks on an unselected button (i.e. X or Z) then the function is triggered, but if he clicks on Y (which is already selected) nothing happens.

Naturally, the best solution would be to fire the function on the onchange event, but IE6 does not fire onchange until the focus is no longer on an element that is not satisfactory.

So, is there a way to find out what the previous value of the switch was, or at least its default value? I could easily create an array of defaults and check for this, but I'm trying to reduce the overhead.

Please no jQuery suggestions ;)

+2


a source to share


2 answers


Use the defaultChecked property of the input element.



You can also use the click event for this, because the click event also fires when the user uses the spacebar / enter key to "check" it.

+2


a source


Well, you can use the onmousedown event on the input elements. It will do what you ask (fire the event when the user clicks), but with onmousedown you can check if this item has already been selected. Example:



document.getElementById('#radio-button-x').onmousedown = function() {
    if (this.checked == true) {
        // was already selected
    } else {
        // not selected, do something
    }
};

      

0


a source







All Articles