Guide to automatically select an option in a dropdown menu using a URL

I am currently working on implementing a dropdown select menu that helps filter an HTML table based on the user's choice. My goal is to utilize the URL of the page to automatically pre-select an option in the dropdown. For instance, if the URL looks like this: , then I want the dropdown option to be set to Product A. I have shared the HTML and CSS code below for reference. If possible, I would prefer to achieve this functionality using JavaScript.

 <div class="filter-section">
      <div class="filter">
        <p class="filter-name">Product</p>
        <select class="dropdown" id="productsDropdown" oninput="filterTable()">
          <option>All</option>
          <option>Product A</option>
          <option>Product B</option>
          <option>Product C</option>
        </select>
      </div>
    </div>
    <!-- filter section end -->
    <!-- table start -->
    <table id="myTable">
      <tr class="header">
        <th style="width: 20%">Name</th>
        <th style="width: 40%">Description</th>
        <th style="width: 20%">Product</th>
      </tr>
      <!-- Access Requests start -->
      <!-- row start -->
      <tr>
        <td>
          <a class="request-link" href="#" target="_blank">Request A</a>
        </td>
        <td>Sit amet consectetur adipisicing elit.</td>
        <td>Product A</td>
      </tr>
      <!-- row end -->
      <!-- row start -->
      <tr>
        <td>
          <a class="request-link" href="#" target="_blank">Request B</a>
        </td>
        <td>Modi placeat quos impedit sit optio doloremque veniam expedita?</td>
        <td>Product B</td>
      </tr>
      <!-- row end -->
      <!-- row start -->
      <tr>
        <td>
          <a class="request-link" href="#" target="_blank">Request C</a>
        </td>
        <td>Lorem ipsum dolor, sit amet consectetur adipisicing elit.</td>
        <td>Product C</td>
      </tr>
      <!-- row end -->
    </table>
    <!-- table end -->
#myInput {
  background-image: url("https://www.w3schools.com/css/searchicon.png"); /* Add a search icon to input */
  background-position: 10px 12px; /* Position the search icon */
  background-repeat: no-repeat; /* Do not repeat the icon image */
  width: 100%; /* Full-width */
  font-size: 16px; /* Increase font-size */
  padding: 12px 20px 12px 40px; /* Add some padding */
  border: 1px solid #ddd; /* Add a grey border */
  margin-bottom: 12px; /* Add some space below the input */
}

#myTable {
  border-collapse: collapse; /* Collapse borders */
  width: 100%; /* Full-width */
  border: 1px solid #ddd; /* Add a grey border */
  font-size: 18px; /* Increase font-size */
  /* display: block;
    overflow: auto;
    height: 500px; */
}

#myTable th,
#myTable td {
  text-align: left; /* Left-align text */
  padding: 12px; /* Add padding */
}

#myTable tr {
  /* Add a bottom border to all table rows */
  border-bottom: 1px solid #ddd;
}

#myTable tr.header,
#myTable tr:hover {
  /* Add a grey background color to the table header and on hover */
  background-color: #f1f1f1;
}

.filter-section {
  display: flex;
  margin-bottom: 6px; /* Add some space below the filters */
  gap: 12px; /* Add some space between the filters */
}

.filter-name {
  font-size: 14px; /* Increase font-size */
  color: #666666;
}

.dropdown {
  border: 1px solid #ddd; /* Add a grey border */
  border-radius: 5px;
  font-size: 16px;
  padding: 1px; /* Add padding */
}

.request-link:link,
.request-link:visited {
  text-decoration: none;
  color: #4050c7;
}

.request-link:hover,
.request-link:active {
  color: #4050c7;
}

I have attempted various solutions found on Stack Exchange but have not been successful so far. I am hesitant to share any code here as nothing has worked for me yet.

Answer №1

Remember to always assign a value to an option! To retrieve the selected option's value, you can utilize SelectElement.value.

To handle changes in the select element, it's recommended to use addEventListener and listen for change events. It's best practice in modern JS to avoid using inline event attributes to maintain separation between HTML and JS.

You will likely need two functions (or methods within a class) to apply or remove the search filter. An if/else statement can help with this process. Additionally, a CSS class should be used to dynamically hide table rows.
An excellent tool to toggle classes based on conditions is classList.toggle(), especially useful when adjusting filters.

While not mandatory, including an URLSearchParams can be beneficial as demonstrated below:

class SearchFilter {
  #Filter;
  #HiddenRows;
  #ProductColumnPosition = 3;
  #ProductCells  = myTable.querySelectorAll(`tbody td:nth-child(${this.#ProductColumnPosition})`);
  #SearchParams = new URLSearchParams(window.location.search);

  constructor(filter) {
    this.#Filter = filter;
    this.#HiddenRows = myTable.querySelectorAll('.d-none');
  }

  setFilter() {
    this.#ProductCells.forEach(cell => {
      cell.closest('tr').classList.toggle('d-none', cell.textContent !== this.#Filter);
      this.#SearchParams.set('productFilter', this.#Filter);
    })
  }

  removeFilter() {    
    this.#HiddenRows.forEach(row => {
      row.classList.remove('d-none');
      this.#SearchParams.delete('productFilter');
    })
    if (this.#Filter === null) {
      productsDropdown.value = "all";
    }
  }
}

// runs the class on selectbox changes
productsDropdown.addEventListener('change', function() {
  updateSearchFilter(this.value);
})

// initially runs to check if a search filter exsist
window.addEventListener('DOMContentLoaded', function() {
  const SearchParams = new URLSearchParams(document.location.search);
  updateSearchFilter(SearchParams.get('productFilter'));
})


// function to run the correct SearchFilter class method
function updateSearchFilter(filter) {
  const Filter = new SearchFilter(filter);
  if (filter === 'all' || filter === null) {
    Filter.removeFilter();
  } else {
    Filter.setFilter();
  }
}
.d-none {
  display: none;
}
<div class="filter-section">
  <div class="filter">
    <label class="filter-name" for="productsDropdown">Product</label>
    <select class="dropdown" id="productsDropdown">
      <option value="all" selected>All</option>
      <option value="Product A">Product A</option>
      <option value="Product B">Product B</option>
      <option value="Product C">Product C</option>
    </select>
  </div>
</div>
<!-- filter section end -->
<!-- table start -->
<table id="myTable">
  <thead>
    <tr class="header">
      <th style="width: 20%">Name</th>
      <th style="width: 40%">Description</th>
      <th style="width: 20%">Product</th>
    </tr>
  </thead>
  <!-- Access Requests start -->
  <tbody>
    <!-- row start -->
    <tr>
      <td>
        <a class="request-link" href="#" target="_blank">Request A</a>
      </td>
      <td>Sit amet consectetur adipisicing elit.</td>
      <td>Product A</td>
    </tr>
    <!-- row end -->
    <!-- row start -->
    <tr>
      <td>
        <a class="request-link" href="#" target="_blank">Request B</a>
      </td>
      <td>Modi placeat quos impedit sit optio doloremque veniam expedita?</td>
      <td>Product B</td>
    </tr>
    <!-- row end -->
    <!-- row start -->
    <tr>
      <td>
        <a class="request-link" href="#" target="_blank">Request C</a>
      </td>
      <td>Lorem ipsum dolor, sit amet consectetur adipisicing elit.</td>
      <td>Product C</td>
    </tr>
    <!-- row end -->
  </tbody>
</table>
<!-- table end -->

Answer №2

After some trial and error, I managed to implement the code below:

let product1 = "Product A";
let product2 = "Product B";
const urlParam = window.location.href;

function displaySelectedProduct() {
  if (urlParam.includes("producta")) {
    document.getElementById("productsDropdown").value = product1;
  } else if (urlParam.includes("productb")) {
    document.getElementById("productsDropdown").value = product2;
  }
}

document.addEventListener('DOMContentLoaded', () => {
  displaySelectedProduct();
});

I encountered some issues with the window.onload event, so I opted to remove it and find an alternative solution. However, the revised implementation should function correctly.

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

"Unexpected end of input encountered while attempting to parse JSON data using JSON.parse

The code snippet below demonstrates how to create a server that retrieves COVID-19 timeline data for the US using Node.js and Express: const express = require('express'); const app = express(); const https = require('https'); const url ...

Steps to insert a column within an HTML document for PDF printing

Is there a way to create an HTML document that can be printed in PDF format but the column feature isn't functioning as expected? Would I need to use a specific library or tool? ...

Puppeteer experiencing issues with missing relative modules and dependencies not being found

After installing puppeteer via npm, I encountered errors when trying to compile it: This dependency was not found: * ws in ./node_modules/puppeteer/lib/WebSocketTransport.js To resolve this, you can run: npm install --save ws These relative modules we ...

Having trouble sending ajax requests in Node.js?

I am currently utilizing a nodejs server for my website, and I am looking to have the backend server initiate a call to an api on an external server. My initial attempt at achieving this was through the following simple and direct method: router.post(&apo ...

The issue of the hamburger icon appearing as "X" seems to only affect certain mobile phones, while it displays correctly on desktops and most other mobile devices. The problem appears to be specifically

On certain mobile phones, the hamburger icon displays as an "X" instead of three horizontal lines. This issue specifically affects all XIAOMI mobile phones on various browsers, while most other devices and desktops show the correct hamburger icon. The < ...

What is the CSS selector used to target elements that are not contained within another selector?

There are numerous nested divs within my code: <div> <div> <div>Apple</div> <div> <div>Banana</div> <div>Grape</div> </div> </div> <div>Craisin</div&g ...

The Mystery of Bootstrap 4 Column Sequence

I was able to achieve this layout using Bootstrap 3, but I am not sure how to implement the same setup with Bootstrap 4 (4.1). My goal is to have a column displaying C beneath A, and another column displaying B. However, on mobile devices, I want all thre ...

How to use Jquery to dynamically alter cell backgrounds in a table based on their values?

I successfully imported the table from MySQL to HTML, as shown below: https://i.sstatic.net/kzJtF.png My script is designed to highlight the two lowest and two highest values in each column: $(document).ready(function(){ var $table = $("#tbTodos"); ...

Tips on avoiding redirection when submitting a form

Upon making an AJAX call to a page, I receive a form with user parameters. This form is later submitted to a URL in order to create a session for the same user in advance. When that person visits the site, they should see their name displayed. To achieve ...

Using selected option from dropdown as a value for a hyperlink

I'm attempting to transfer the chosen value from a dropdown menu to my link. This way, when I click on the specific link, it should trigger the corresponding action based on the ID selected from the dropdown. The alert shows the value, but now I need ...

Error in Next.js: The function (0 , firebase_auth__WEBPACK_IMPORTED_MODULE_1__.onAuthStateChanged) is not defined as a function

Just starting out with Next.js development and currently following a Youtube tutorial on creating a Whatsapp clone using firebase8.9 as the database. I am looking to implement a feature where the app checks if the user is logged in, if so redirect them to ...

The step-by-step guide on displaying API choices in an Autocomplete feature and keeping them up

Having trouble with updating autocomplete options. An error message pops up in the console log when I try to deselect a tag or select a new one: MUI: The value provided to Autocomplete is invalid. None of the options match with [{"catName":{&qu ...

Leveraging Jquery to retrieve multiple values for dynamic updating in HTML

As I ponder over this dilemma, a suitable title eludes me to encapsulate my query. Behold the code in question: $(document).ready(function() { setInterval(function(){ $.get('/battleship/update_game/{{info.gameid}}/{{user.username}}', ...

React TSX file not recognizing JSON data stored in an HTML data attribute

I am having some trouble with implementing the password toggle component from the Preline UI. Here is how the component looks: "use client" import React, { ChangeEvent, MouseEventHandler, useEffect } from "react"; export default functi ...

Update a specific form data field within an Angular application

I recently encountered a situation where I had an angular form with 9 fields and submitted it to the server using a post request. However, I realized that I had only filled in values for 8 fields while leaving one as null. Now, in a new component, I am w ...

Utilizing React.js components for Parsing JSON Objects

As a beginner in reactjs, I am faced with the challenge of parsing JSON response fetched from an API in index.html and passing it to a component called Card.js as props. Despite being able to access the response in the console log, I am unable to render it ...

I am eagerly awaiting for the table command "rowspan" to finally start functioning properly. Right now, it seems to be completely ignored

While working on my html project to create a basic table, I encountered an issue halfway through. My goal was to make the second to last row double in size by using rowspan="2", but unfortunately nothing changed. Can someone assist me with this problem? ...

Issue with Angular2: The [routerLinkActive] directive does not update when using _router.navigate

My app includes several routerLinks that I have styled using [routerLinkActive]="['active']". Everything works perfectly when I click on one of the routerLinks to navigate. However, when I try to navigate using: this._router.navigate( [ thisUrl ...

Issue with hasClass and addClass not working as expected

Why isn't the script below adding a class (.active) to .global-header when .navigation.primary has a class of .active? JS if($(".navigation.primary").hasClass("active")) { $('.global-header').addClass('active'); } HTML < ...

Managing spinners in Protractor when they are concealed by a wrapper element

While writing a test for an Angular app using Protractor, I encountered several issues with handling spinners. I managed to solve some of them, but I'm unsure how to test spinners that are hidden by a wrapper. For instance, when the parent tag has ng- ...