Charlotte Mays Charlotte Mays - 1 year ago 91
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: )

$('#id_repeat_type').on('change', function() {
if (this.value == 'NR')

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:

What am I missing?

Answer Source

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=""></script>
<form action="/tasks/19" method="post">
  <input type="submit" value="Save" />

  <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>

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download