Question

I need to write some jquery which will read what the current value in a drop down list is and then hides a particular link on the page.

The dropdown list is a locale selector. So when I select "english" I want the link to be hidden but when select French the link has to remain.

Can you show how i can do this? I want learn this. Thanks

Was it helpful?

Solution

How about this:

function handleLang() {
    if ($('#select').val() == 'en') {
        $('#link').hide();
    } else {
        $('#link').show();
    }
}
$(function() {
    // hide/show on load
    handleLang();

    // hide/show when the language is changed (useful if the page doesn't reload)
    $('#select').change(handleLang);
});

OTHER TIPS

Based on the first answer provided for this question and more hints provided by the author of the first answer in the comments, here is the final (and compact) full version of the code that worked for me (I also removed and styling since was no longer required). This is a main page provided in the index.html.erb for this test application.

<h2 id='main_header'>Showing/hiding link based on dropdown selection</h2>

<table>
  <thead>
    <th>Action</th>
    <th>Skip assessment</th>
    <th>Reason for skipping</th>
  </thead>
  <tbody>
    <tr>
      <td>
        <%= link_to 'Start asseement', url_for(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...' %>
      </td>
    </tr>
  </tbody>
</table>

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

The start assessment page is very basic, just a title and back link to the main page contained in the start_assessment.html.erb file:

<h1>Assessment</h1>

<%= link_to 'Back', :back %>

I this is of any help, here are the controller home_controller.rb file:

class HomeController < ApplicationController
  def index
  end

  def start_assessment
  end
end

And the route route.rb file is:

Rails.application.routes.draw do
  root controller: 'home', action: :index
  get 'start_assessment' => 'home#start_assessment'
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top