L.D
L.D

Reputation: 1329

Rails - text_field_tag not showing up with Javascript

I have vary basic index page with a drop down Yes/No selection. Default is No. When Yes is selected I want to have a text input tag displayed so I can enter a reason for skipping an assessment. If No is selected the text input field should be removed.

Here is my code:

<h1 id='main_header'>test-01</h1>

<table>
  <thead>
    <th>Action<//th>
    <th>Skip assessment</th>
    <th>Reason for skipping</th>
  </thead>
  <tbody>
    <tr>
      <td>
        <%= link_to 'Start asseement', controller: :home, action: :start_assessment, id: 'start_assessment' %>
      </td>
      <td>
        <%= select_tag "skip_option", options_for_select([ "Yes", "No" ], "No"), id: "skip_option", :onchange => "reason_picker()" %>
      </td>
      <td>
        <%= text_field_tag "reason_for_skipping", nil, size: 50, placeholder: 'Enter reason here...', style: "display: none;" %>
      </td>
    </tr>
  </tbody>
</table>

<script>
  $(document).ready (
    function reason_picker () {
      var selected = document.getElementById("skip_option").selectedIndex;
      alert(selected);
      if (selected == 0) {
        $("#reason_for_skipping").show();
        alert("if");
      }
      else {
        $("#reason_for_skipping").hide();
        alert("else");
      }
    }
  );
</script>

I am always getting the "else" branch, selected index is always 1 and when selecting Yes from the drop down (this should be selected index 0), the text input tag is never shown. Don't know how to fix this.

Upvotes: 0

Views: 155

Answers (1)

Hieu Pham
Hieu Pham

Reputation: 6707

The problem is in this line

<%= select_tag "skip_option", options_for_select([ "Yes", "No" ], "No"), id: "skip_option", :onchange => "reason_picker()" %>

reason_picker() will be undefined

To fix it, you may easily refactor your javascript like this:

<script>
  $(document).ready (
    window.reason_picker = funtion() {  # <-- change here
      var selected = document.getElementById("skip_option").selectedIndex;
      alert(selected);
      if (selected == 0) {
        $("#reason_for_skipping").show();
        alert("if");
      }
      else {
        $("#reason_for_skipping").hide();
        alert("else");
      }
    }
  );
</script>

Upvotes: 1

Related Questions