0

I have a set of 4 radio buttons, which when clicked show/hide divs on my page.

On unsuccessful validation of my form I return the user back to the form with last clicked radio button checked.

The issue I have is it does not show/hide the divs as in this instance the radio button isnt being clicked.

What I want to be able to do is on page load detect which radio button is checked and then fire a click event. (ie simulate someone clicking that radio button) so that it then shows/hides my divs.

My code to show hide looks like this

$('#showduo').click(function(){
$('div[id^=div]').hide();
$('#div1').show();

html:

<input type="radio" name="type" value="Single" id="hideall" <?php echo set_radio('type', 'Single', TRUE); ?> />
<input type="radio" name="type" value="Singleplus" id="showsingleplus" <?php echo set_radio('type', 'Singleplus'); ?> />
<input type="radio" name="type" value="Duo" id="showduo" <?php echo set_radio('type', 'Duo'); ?> />
<input type="radio" name="type" value="Family" id="showfamily" <?php echo set_radio('type', 'Family'); ?> />

<div id="div1" style="display:none;">

1 Answers1

0

If you call .click() without any parameters on the selected radio button it will execute the click handler for that button, just as if the user clicked on it.

Try:

$('input:radio[name=xxx]:checked').click();

Of course, you have to change "xxx" to the name you gave the radio buttons.

Note: I feel compelled to say that I wouldn't have it so each radio button has its own handler. That means you have to add JavaScript if you want to add another radio button.

John S
  • 21,212
  • 8
  • 46
  • 56
  • This does exactly what I want it to do. I had an issue where I had placed this code above the code that worked on the click function. But after moving it down below it works perfectly. Am not sure what you mean by your note though. As in i am not sure how else I would do it – Scott Goodman Apr 07 '13 at 07:02
  • @Scott Goodman - In case you are interested, I created a [jsfiddle](http://jsfiddle.net/john_s/gwHNu/1/) that demonstrates how you could set this up so you have just one handler and wouldn't have to change the JavaScript if you add another radio button. Let me know if you find it of any value. – John S Apr 07 '13 at 15:57