Change the dropdown menu text to show the selected option text once the page has been redirected

Hey there, I am looking to dynamically update the dropdown text with the selected option after a page redirect and reload of the dropdown. Check out my code below:

<div class="sorting-option">
    <select id="selectdropdown" class="dropdown-select">
        <option value="">Recommended Items</option>
        <option value="?sort1desc=F&sort1=Item_NAME">Name (A-Z)</option>
        <option value="?sort1desc=T&sort1=Item_NAME">Name (Z-A)</option>
        <option value=".f?sort1desc=F&sort1=Item_ONLINECUSTOMERPRICE">Price (Low-High)   
        </option>
        <option value=".f?sort1desc=T&sort1=Item_ONLINECUSTOMERPRICE">Price (High-Low) 
        </option>
    </select>
</div>

Currently, every time I select an option from the dropdown, the page loads but only shows the "Recommended Items" option instead of the one I selected. For example, if I choose "Name (Z-A)", I expect the dropdown text to update accordingly after the page loads.

I've attempted this code to achieve the desired result, though it hasn't worked as expected:

$(document).ready(function () {
        $('#selectdropdown').change(function () {
            location.href = $(this).val();
            $("#selectdropdown option:selected").text();
        });
    });

Answer №1

To incorporate the selected attribute into options within the <select> tag, simply include a name attribute in the select element. Upon form submission, retrieve the value and implement a condition to automatically select the item after the page has loaded.

<if selectdropdown = "sort1desc=F&sort1=Item_NAME"> selected<endif>

For example:

<div class="sorting-option">
    <select id="selectdropdown" class="dropdown-select" name= "selectdropdown">
        <option value="">Recommended Items</option>
        <option value="?sort1desc=F&sort1=Item_NAME" <if selectdropdown = "sort1desc=F&sort1=Item_NAME"> selected<endif> >Name (A-Z)</option>
        <option value="?sort1desc=T&sort1=Item_NAME">Name (Z-A)</option>
    </select>
</div>

Repeat this setup for all available options.

Answer №2

Here are the steps you can follow.

  1. Include the selected value in the URL.

  2. Upon page load, retrieve the values from the URL to automatically select the value.

$(document).ready(function() {
  $("#social").change(function(event) {
    var target_url = $(this).val();
    //include the target URL in the URL scope
    var redirect_url = target_url + "?social=" + target_url;
    location.href = redirect_url;
  });

  //on page load retrieve the URL values to auto-select it from dropdown.
  var urlvars = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  var keys = urlvars[0].split('=');
  var default_select = keys[1];
  $('#social').val(default_select);

});
<form>
  <select id="social">
    <option value="http://localhost/index.cfm">Default</option>
    <option value="http://localhost/a.cfm">Google</option>
    <option value="http://localhost/b.cfm">Facebook</option>
  </select>
</form>

Answer №3

Looking to dynamically update a select box based on the url parameter "sort1desc"? Check out this snippet of jquery code below.

$(document).ready(function () {
    var sortParam = getUrlParameter("sort1desc");
    alert(sortParam);
    $('#selectdropdown option').each(function() {
        var str = $(this).attr('value');
        if(str.indexOf("sort1desc="+sortParam) >= 0) {
            $('#selectdropdown').val($(this).attr('value'));
        }
    });
    $('#selectdropdown').change(function () {
        location.href = $(this).val();
        $("#selectdropdown option:selected").text();
    });
});
function getUrlParameter(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) 
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) 
        {
            return sParameterName[1];
        }
    }
}

Answer №4

To save the selected value, you can utilize localStorage.getItem() and localStorage.setItem();. Afterwards, in your ready-function, you can reselect the saved value.

For more information on localStorage, visit: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#localStorage

$(document).ready(function() {
    var opt = document.querySelector('#selectdropdown option[value="' + localStorage.getItem('selectdropdownselectedvalue') + '"]');
    if (opt) opt.selected = true;

    $('#selectdropdown').change(function() {
        localStorage.setItem('selectdropdownselectedvalue', document.querySelector('#selectdropdown').value);

        location.href = $(this).val(); //instant redirect
        //$( "#selectdropdown option:selected" ).text(); <-- not possible because js is already about to redirecting
    });
});

Here's a working example without using jQuery:

<select id="selectdropdown" onchange="changed(this)">
    <option>nothing</option>
    <option value="2">2</option>
    <option value="4">4</option>
    <option value="6">6</option>
    <option value="8">8</option>
</select>
<script>
    var opt = document.querySelector('#selectdropdown option[value="' + localStorage.getItem('selectdropdownselectedvalue') + '"]');
    if (opt) {
        opt.selected = true;
    }

    function changed(dd) {
        localStorage.setItem('selectdropdownselectedvalue', document.querySelector('#selectdropdown').value);
        window.location = location.href;
    }
</script>

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

How can I implement a hover-over image change effect similar to the one seen in Gmail accounts?

I am attempting to implement a feature that allows users to change their image, similar to what can be done in a GMail account. When the user hovers over the image, an option to "change image" should appear. This may be a new concept for me because I am ...

Complete the modal window form

I'm currently facing an issue with populating a modal window form. To provide some context, when I click on a grid row to edit a user, I make an ajax call which fetches specific data related to that user. Here is the existing code snippet: <modal ...

I am struggling to retrieve a value from the angular.forEach function, the flag value is not being obtained. What could be

I'm having an issue with my controller.js file. I can't seem to access the value from the angular.forEach function, specifically the flagvalue isn't being retrieved. Is it because the scope of flagvalue ends when the forEach function complet ...

Utilize javascript to activate the hyperlink

Clicking the following link will open a video: <a href="<?php echo $rows['image1'] ; ?> " rel="vidbox" title="<?php echo $rows['name']." <br>".nl2br($rows['detail']) ; ?>" id="m2"><?php ...

Observing the timepiece malfunctioning beyond expectations

Let me explain the issue here in a simple way. I have a parent component where I execute a method that changes a property value of an object called products. This is working fine. However, when I pass this object as a prop to a child component and watch i ...

Releasing Typescript 2.3 Modules on NPM for Integration with Angular 4

Although there are instructions available in Writing NPM modules in Typescript, they are outdated and there are numerous conflicting answers that may not be suitable for Angular. Additionally, Jason Aden has delivered an informative presentation on youtu ...

Numerous buttons activating a single modal component

I have an array called videos, which contains objects of the type Video (defined below). My goal is to create a functionality where clicking on a specific video button opens a modal containing information about that particular video. interface VideosInfo ...

Using JSON Object for Default Selection in an Angular Dropdown Menu

Here is some code I have that fills in a specific select item on a webpage: <select ng-model="activity.selectedParent" ng-options="parent as parent.title for parent in parents track by parent._id"></select><br> I'm curious if there ...

Activate the click function of an asp.net linkbutton when the mouse enters by utilizing jQuery

I'm attempting to create a hover-triggered click event using jQuery. While this is a straightforward task, I've run into an issue where I can't seem to trigger the click event of an ASP.NET link button that refreshes the content of an updat ...

Unable to successfully cancel requestAnimationRequest in a React component when using hooks

I'm currently working on a progress bar project where I aim to halt the animation (using cancelAnimationRequest) once it reaches a specific value (10, 100, ... N) and reset it back to 0. Unfortunately, in my existing code, although it resets to 0, th ...

Responses Loop Continuously Changing

Could someone take a look at this section of my script and provide some feedback? The script is triggered whenever a response is submitted, and its purpose is to turn a column of data containing text strings into clickable hyperlinks to edit each response. ...

Retrieving text content from multiple classes with a single click event

There are numerous elements each having class names p1, p2, p3,...p14. Consequently, when attempting to extract text from the clicked class, text from all classes is retrieved! For instance, if the expected text is 80, it ends up being 808080080808080808 ...

When working with Vue 3, remember that inject() function is only allowed within setup or functional components

I'm puzzled as to why I keep encountering this error. I am attempting to utilize the Vuex store in a composition function, but for some reason, it keeps throwing an error regarding inject (even though I'm not using inject at all). My application ...

Setting up lint-staged for Vue projects: A step-by-step guide

After setting up a new Vue3 app using the Vue CLI and configuring Prettier as my linter, I decided to implement commitlint, husky, and lint-staged for validating commit messages and linting the code before pushing it. My Approach Following the instructio ...

Switch up the appearance of a document by manipulating the stylesheet using a select tag

I'm currently facing an issue with the implementation of a drop-down box on my website for selecting different themes. Despite having the necessary javascript code, I am unable to get it working correctly. Here's the snippet: //selecting the sele ...

Why is it necessary to create a new object in Node.js to establish a server?

After reviewing the information about socket.io, there is one aspect that I find confusing. I understand that to create a server, it can be done like this: var io = require ("socket.io")(); However, I am curious about why it necessitates creating a new ...

Internet Explorer causing issues with Jasmine mocking ajax calls

Recently, I attempted to develop a spec that enables mocking out Ajax calls. The testing procedure functions seamlessly on browsers such as Chrome and Firefox; however, I encountered some difficulties while executing the test case on Internet Explorer (spe ...

Operating two independent Angular applications simultaneously on a single webpage

I'm currently developing an application that allows multiple Angular applications to be embedded within a main frame. Currently, I am using IFrames for this purpose, which is functioning well but has its limitations. I am exploring ways to embed ano ...

Extracting information from a webpage by using Javascript to locate and interact

Seeking a way to retrieve the src attribute from an audio tag dynamically inserted into the DOM by third-party JavaScript without the ability to modify it. The goal is to back up these sounds by capturing their sources on the server side across multiple pa ...

The BG column image is not stretching to full height

I am facing an issue with my website layout where the left column has a background image and another background image is set for the body to fill the rest of the screen. The content area on the right extends vertically beyond the browser window height. How ...