Charlotte Mays Charlotte Mays - 5 months ago 8
jQuery Question

jQuery function won't run when removed from context

This code has the behavior I want, but I want the behavior to also occur when the page initially loads:
(jsfiddle: https://jsfiddle.net/1px1t57s/ )

$(document).ready(function(){
$('#id_repeat_type').on('change', function() {
if (this.value == 'NR')
{
$("#repeat-options").hide();
}
else
{
$("#repeat-options").show();
}
});
});


My first thought was to use "change load" or "change ready" instead of just "change", but this didn't change the behavior (possibly because the function is already wrapped in $(document).ready?)

My next thought was to pull the function out and run it separately as well as on change, but when I removed the function, it broke the existing functionality: https://jsfiddle.net/1px1t57s/1/

What am I missing?

Answer

Invoke .change() to call change-handler initially

Note that toggle with Boolean could be used to show/hide elements

$(document).ready(function() {
  function toggle_options() {
    $("#repeat-options").toggle(this.value != 'NR');
  };
  $('#id_repeat_type').on('change', toggle_options).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form action="/tasks/19" method="post">
  <input type="submit" value="Save" />
  <br>

  <label for="id_task_name">Task name:</label>
  <input style="width: 100%" id="id_task_name" maxlength="400" name="task_name" type="text" value="sample task" />

  <label for="id_repeat_type">Repeat type:</label>
  <select id="id_repeat_type" name="repeat_type">
    <option value="NR" selected="selected">No Repeat</option>
    <option value="IA">Repeat After X Days</option>
    <option value="IE">Repeat Every X Days</option>
  </select>

  <div id="repeat-options">
    <label for="id_repeat_days">Days between instances:</label>
    <input id="id_repeat_days" name="repeat_days" type="number" />
  </div>

  <br>
  <input type="submit" value="Save" />
</form>