2

I'm trying to do something. I have the following code:

<form>
<input type='radio' name='radio_flavour' checked/>Unique flavour<br/><input class='double-flavoured' type='radio' name='radio_flavour'/>Double flavoured<br/>
<select>
<option>Select the second flavour...</option>";
foreach($connection->query($sql3) as $flavour)
{
    echo "<option value='{$flavour['flavour_id']}'>{$flavour['flavour_name']}</option>";
}
echo "
    </select>
</form>

What I need is when the second radio button radio_flavour with the class double-flavoured is selected, the HTML select under it will be enabled and vice-versa. I'm trying with this jQuery code:

$('.double-flavoured').change(function()
{
    var setE =  $(this).is(':checked') ? true : false;
    $(this).nextAll('select').first().attr('disabled', setE);
});

But this don't work!
How to do this with jQuery? Thanks!

4
  • 1
    You should use value to distinguish the different choices in a radio button group.
    – Barmar
    Apr 17, 2015 at 21:37
  • Have you considered generating a minimal example using jsfiddle?
    – steven
    Apr 17, 2015 at 21:37
  • 1
    Where's your javascript?
    – romuleald
    Apr 17, 2015 at 21:38
  • @romuleald I forgot it, sorry. I've updated the question!
    – Dyan
    Apr 17, 2015 at 21:41

1 Answer 1

4

Your code only runs when you click on the second button, not when you click on the first, since it doesn't have the double-flavoured class. You need to attach the handler to all the buttons in the group, and then test whether the one being selected has the class.

$(":radio[name=radio_flavour]").click(function() {
  $(this).nextAll('select').attr('disabled', !$(this).hasClass("double-flavoured"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type='radio' name='radio_flavour' checked/>Unique flavour
  <br/>
  <input class='double-flavoured' type='radio' name='radio_flavour' />Double flavoured
  <br/>
  <select disabled>
    <option>Select the second flavour...</option>";

    <option value="1">Flavour 1</option>
    <option value="2">Flavour 2</option>
    <option value="3">Flavour 3</option>

  </select>
</form>

3
  • Warn about using is possibly dangerous if the HTML come to change
    – romuleald
    Apr 17, 2015 at 21:44
  • @romuleald I don't understand what you're saying.
    – Barmar
    Apr 17, 2015 at 21:48
  • Thank you, Barmar! Worked like a charm! I think this will help a lot of people. A great hug! :)
    – Dyan
    Apr 17, 2015 at 21:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.