Search code examples
javascriptjqueryjquery-callbackjquery-events

How do I trigger an initial change event for radio buttons with jquery?


I'm trying to enable/disable an "other" field at the bottom of a set of radio buttons, like so...

enter image description here

window.init = function() {
  debugger;
  var form = $("#myform");
  var enableOther = function() {
    var other = $(this).val() == 'other';
    form.find('input[name=other]').prop('disabled', !other);
  };
  var options = form.find('input:radio[name=myradio]');
  options.change(enableOther);

  //now I want to call the on-change handler to update the initial disabled value
  $.proxy(enableOther, options)(); //these don't work
  //options.trigger('change');
  //options.triggerHandler('change');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="debugger; init();">Init</button>

<form id="myform">
  <ul>
    <li><input type="radio" name="myradio" value="1" />Item 1</li>
    <li><input type="radio" name="myradio" value="2" />Item 2</li>
    <li><input type="radio" name="myradio" value="3" />Item 3</li>
    <li><input type="radio" name="myradio" value="other" />Other</li>
    <li><input type="text" name="other" /></li>
  </ul>
</form>

(click Init, select Other, click Init again, and the field incorrectly becomes disabled)

This works fine when clicking through each item, but I want to be able to have my .change() jquery callback trigger once in the init function (this snipped goes into a popup form with persisting values). I've tried .proxy and trigger, but I seem to be getting all radio buttons and .val() is the individual value, not the selected one.

How should I be artificially triggering this callback?


Solution

  • Radio buttons are odd.

    In your callback use the selector for the one that is checked.

    var myval = $('input[type="radio"][name="myradio"]:checked').val();
    var other = myval == 'other';
    

    Note: use [type="radio"] not the :radio as it allows the selector to be more efficient when browsers support that.

    Test: to prove the concept, set the OTHER prior to calling the init:

    $('input[type="radio"][name="myradio"]').eq(3).prop('checked',true);
    

    and then the one that is NOT:

    $('input[type="radio"][name="myradio"]').eq(2).prop('checked',true);
    

    THEN use what you tried:

    options.trigger('change');