views:

30

answers:

2

I have a form to create a Ruby on Rails object. A part of the form uses radio buttons to choose an attribute. I then use jQuery UI to display the buttons, like so.

<head>
<script type="text/javascript">
    $(document).ready(function() {
        $("#typeRadios").buttonset();
    });
</script>
</head>
<body>
<div id="typeRadios">
    <input id="character_chartype_a" name="character[chartype]" type="radio" value="A" /><label for="character_chartype_a">A</label>
    <input id="character_chartype_b" name="character[chartype]" type="radio" value="B" /><label for="character_chartype_b">B</label>
</div>
</body>

This all works fine. I click a button, and then when the form is submitted the attribute is saved correctly.

The problem is, I need to be able to click one of the buttons programmatically. At the moment, I'm doing this:

// data.chartype = a
$("label[for='character_chartype_"+data.chartype+"']").click();

This works in the sense that visually the button appears clicked, but when the form is submitted, the attribute isn't saved. What is causing this behaviour? Thanks for reading.

EDIT: fixed typo

A: 
  1. an id has to be unique. just a c&p failure?
  2. why not "click" the radio button directly?
$("#character_chartype_" + data.chartype).click()
john_doe
Because it's jQuery UI - see this previous question: http://stackoverflow.com/questions/3593301/how-can-i-simulate-a-click-on-a-jquery-ui-radio-button
Yi Jiang
@YiJiang - Clicking the `<label>` wasn't the right solution :) jQuery UI provides a method for updating a programmatically changed selection :)
Nick Craver
+2  A: 

You should click the radio button directly like this:

$("#character_chartype_" + data.chartype).click();

It does click the button, you just need to tell jQuery UI to refresh it's visual state afterwards using the refresh method, like this:

$("#typeRadios").buttonset("refresh");

So overall this should do it:

$("#character_chartype_" + data.chartype).click();
$("#typeRadios").buttonset("refresh");
Nick Craver
@Nick - Thanks - I was looking for that option a while back too
Yi Jiang