Concealing a hyperlink depending on the value chosen in a dropdown menu

Looking for guidance on how to use jQuery to read the current value of a drop-down list and hide a specific link based on that value.

The drop-down list is for selecting the language/locale. For example, when "English" is selected, I want the link to be hidden. However, if "French" is selected, the link should remain visible.

Could someone demonstrate how this can be achieved? Eager to learn. Thank you!

Answer №1

Consider the following solution:

function toggleLanguageLink() {
    if ($('#language-choice').val() == 'english') {
        $('#link-to-translate').hide();
    } else {
        $('#link-to-translate').show();
    }
}
$(function() {
    // hide/show the link based on current language selection
    toggleLanguageLink();

    // update link visibility when language is changed (useful for dynamic pages)
    $('#language-choice').change(toggleLanguageLink);
});

Answer №2

The final code version that worked for me based on the first answer and additional hints from the author includes a compact form without any styling. This code is for the main page in the index.html.erb file of the 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 simply contains a title and back link to the main page, located in the start_assessment.html.erb file:

<h1>Assessment</h1>

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

For reference, here is the home_controller.rb file which includes the index and start_assessment methods:

class HomeController < ApplicationController
  def index
  end

  def start_assessment
  end
end

Finally, the route.rb file has the following routes:

Rails.application.routes.draw do
  root controller: 'home', action: :index
  get 'start_assessment' => 'home#start_assessment'
end

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm struggling to locate the space that should be between these elements

After accidentally starting in quirks mode without declaring a doctype, I realized my mistake and corrected it by declaring a doctype. However, there is a persistent issue with a space between .car-box-img and car-box that I can't seem to locate in t ...

Utilizing JavaScript and Node to create a multidimensional array of objects across multiple datasets

I'm facing an issue with this problem. Are there any differences between the arrays in the examples below? Here's one in React: const multiDataSet = [ { columns: [ {title: "Last name", width: {wpx: 150}} ...

Error: Required variable missing in AJAX Post request

When making an ajax call, I use the following code: o.open("POST",q,true); o.setRequestHeader("Content-type","application/x-www-form-urlencoded"); o.setRequestHeader("Content-length",p.length); o.setRequestHeader("Connection","close"); Here, q represent ...

What is the process for accessing the data attributes of div elements and then transferring them to a cookie?

Although this question may have been answered before, I couldn't find a specific solution. Imagine I have the following div elements... <div class="listings-area"> <div itemtype="http://schema.org/Product" itemscope=""> <a class="lis ...

Encountered an error loading resource: server returned a 404 status code while utilizing Angular framework and deploying via GitHub Pages

Currently facing an issue with my Angular website deployment on Github Pages, receiving a console error "Failed to load resource: the server responded with a status of 404 ()" at "home: 1". This error specifically seems to be related to the app.component ...

Will upgrading jQuery UI 1.7.2 to 1.8.7 lead to enhanced performance?

My website relies solely on jQuery UI dialogs and buttons. Everything seems to be functioning well overall, but some users have reported occasional performance issues where the system is not as responsive as they would like. I noticed that upgrading from ...

Guide to incorporating external CSS and JavaScript into an Angular 2 project with Express.js and Node.js

As a newcomer to Angular2 and NodeJs, I am eager to learn how to integrate external CSS and JS in an Angular2 and Nodejs express app. Specifically, I am looking to integrate a bootstrap admin theme into my Nodejs application. The screenshots below provide ...

Learn the process of creating test cases using `ava` for the following code snippet

const TimeToEvent = minutes => { const oneMinute = 1; const minutesInAnHour = 60; if (minutes <= oneMinute) { return "in just 1 minute"; } if (minutes < minutesInOneHour) { return "in mere&quo ...

Can Backbone be used to retrieve a local JSON file?

I have a simple and validated local JSON file that I am trying to fetch using Backbone.js. Here is the snippet of Backbone.js code: MyModel = Backbone.Model.extend({ defaults:{ name: '', age: 0 } }); MyCollection =Backbo ...

Displaying a division when a button is pressed

Despite my best efforts, I can't seem to get the chosen div to show and hide when the button is pressed. <button id="showButton" type="button">Show More</button> <div id="container"> <div id="fourthArticle"> <i ...

Mastering the Art of Promises in RXJS Observables

After thoroughly researching SO, I stumbled upon numerous questions and answers similar to mine. However, I suspect that there might be gaps in my fundamental understanding of how to effectively work with this technology stack. Currently, I am deeply enga ...

Creating a hover effect for a specific card while maintaining the rest of the cards unaffected

When hovering over a card, all icons are displayed instead of just the icons for that specific card. I want to show only the icons for the card being hovered on (example output: image). The cards are generated automatically using v-for and fetching data fr ...

Gain access to Google Analytics without the need for page consent by utilizing JavaScript

I am currently building a dashboard with Atlasboard. My goal is to retrieve Google analytics data such as page views, and I plan to run specific queries which can be found here. Is there a method to access my Google analytics data without the consent pag ...

Defining data types for an array of objects in a useState hook

I'm having trouble understanding the issue with my code. interface dataHistory { data: string, before: string | number, after: string | number, } I have an interface defined outside of the Functional Component and inside I specify its struct ...

display a div positioned relatively next to another div

I'm having trouble displaying a textbox next to another div on my webpage. Instead of appearing next to the div, it is showing up below it. The textbox needs to have an absolute position. You can see the issue in action by checking out this demo. Than ...

How can JavaScript be used to remove HTML tags from text while preserving a space between each line?

I found a helpful solution on Stack Overflow for removing HTML from text content. This is the method it suggests: function strip(html){ let doc = new DOMParser().parseFromString(html, 'text/html'); return doc.body.textContent || "&quo ...

Bug in Chrome (Win) causing middle-mouse-button overflow issue

Take a look at this demo: http://jsfiddle.net/pixelfreak/AN5Wb/ Everything works perfectly until attempting to scroll using the middle mouse button. At that point, you can see beyond the boundaries of the element. This issue does not occur in Firefox or ...

What could be the reason for PassportJS in Node failing to clear the session upon logout?

I am encountering an issue with my system not successfully logging out using PassportJS. The logout route appears to be triggered, but the session is not being removed as intended. I would like it to return a 401 error if the user is not logged in on a spe ...

Why is it not possible for me to choose an element after it has been placed within a grid component?

Struggling to eliminate the blur effect on an image inside a grid element? It seems modifying the properties of an element within a grid class is causing some issues. To simplify, I conducted a basic test: I managed to change the ppp2 class when hovering ...

Is it necessary for a TypeScript Library's repository to include the JavaScript version?

Is it necessary to include a JavaScript version of the library along with the Typescript repository for consumers? Or is it best to let consumers handle the compilation process themselves? Or should I consider another approach altogether? ...