Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery click / change function on radio button set

Tags:

jquery

I have a radio button set called "pick_up_point". There are 3 options and clicking on an option will display a set of input fields relevant to the option.

Now by default when the user clicks on an option I run the change() function which will run a function called "clearInputFields" - which as you might guess will clear out any text entered in the input fields.

$("input[name='pick_up_point']").change(function()
{
 clearInputFields(); 
});

Now I have tried extending this so that a prompt is displayed to the user to let them know that the input fields will be cleared:

$("input[name='pick_up_point']").click(function(event)
{
 if(confirm('Address details will be cleared. Continue?'))
 {
  return true;
 }
 else
 {
  return false;
 }
});

The 'click' function is before the 'change' function.

This works "OK" in Firefox and does not work properly in IE.

In Firefox the radio button gets selected and the prompt is displayed, and clicking on the Cancel button will go back to the previous option with all values retained.

In IE the radio button gets selected and the prompt is displayed but the values get cleared out. If you click Cancel then no radio button is selected.

The way I would like this to work is if you click another radio button it should not select it unless you click OK on the prompt. If you click Cancel the values should be retained.

like image 425
MAX POWER Avatar asked Aug 09 '10 12:08

MAX POWER


1 Answers

In IE, the change event on checkboxes and radio buttons doesn't fire immediately, but only after the field has been unfocused. In this way it behaves like text input boxes.

jQuery monkeys about with the change event quite significantly, in a way that hides this behaviour from you. However it is unable to accurately reproduce the behaviour of other browsers in IE, so in some cases it will trigger change in response to interaction with an element even when another click event handler tries to preventDefault.

Another problem: in IE, if you return false from click on a radio button, the new radio button won't get checked, but the previous button will still lose its checkedness, leaving you with no radios checked!

So you'll probably have to do some kind of annoying state-tracking, and manually put the radio buttons back to their old state when the confirm is refused. eg.:

var currentradio= $("input[name='pick_up_point']:checked")[0];
$("input[name='pick_up_point']").change(function(event) {
    var newradio= $("input[name='pick_up_point']:checked")[0];

    if (newradio===currentradio)
        return;
    if (confirm('Address details will be cleared. Continue?')) {
        clearInputFields();
        currentradio= newradio;
    } else {
        currentradio.checked= true;
    }
});
like image 191
bobince Avatar answered Sep 27 '22 21:09

bobince