Automatically select and pre-fill a list item based on its value using jQuery

I'm a beginner in JQuery. In my application I have the following:

Here is my HTML code:

<ul id="list">
    <li>
        <a class="selected" value="0" href="#"  id="sel">ALL</a>
    </li>
    <li>
        <a href="#"  value="1">1+</a>
    </li>
    <li>
        <a href="#" value="2">2+</a>
    </li>
    <li>
        <a href="#" value="3">3+</a>
    </li>
    <li>
        <a href="#" value="4">4+</a>
    </li>
    <li>
        <a href="#" value="5">5+</a>
    </li>
</ul>

<input type="hidden" id="hdn_list" value=""></input>

This is my CSS code:

.selected{background-color:green;}

Below is my JQuery code for retrieving the selected list value:

$(document).ready(function () {
    $('#list li a').click(function () {
        var listValue = $(this).attr("value");
        $("#hdn_list").value = listValue;          //passing the new selected values to hidden control
        $('#list li a').removeClass('selected');
        $(this).addClass('selected');
        return false;
    });
});

When I click the submit button, it redirects to the next page. If I go back to this page, it should pre-fill the selected value using the hidden control (#hdn_list) value and apply the CSS style to that selected value. How can I achieve this using jQuery/javascript? Thank you in advance.

Answer №1

Give this a try

 $(document).ready(function () {
    $('#list li a').click(function (e) {
        var value = $(this).attr("value");
        localStorage.setItem("menu", value);
        $("#hdn_list").val(value); //passing the new selected values to hidden control
        $('#list li a').removeClass('active');
        $(this).addClass('active');
        e.preventDefault();
    });
      var retrievedObject = localStorage.getItem('menu');
      if (retrievedObject != null) {
        $('ul li a').removeClass("active")
        $('ul li a[value="' + retrievedObject +'"]').addClass('active');
      } else {
        $('ul li a:eq(0)').addClass('active');
      }
});

See DEMO

Answer №2

To prevent the default action in jQuery, use the event.preventDefault() method. This will stop the default behavior of an event.

$(document).ready(function () {
    $('#list li a').click(function (event) {
      event.preventDefault();
        var newValue = $(this).attr("value");
        $("#hdn_list").value = newValue;          //passing the new selected values to hidden control
        $('#list li a').removeClass('selected');
        $(this).addClass('selected');

    });
});

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

Special characters like greater/less than signs have not been properly encoded

I am currently facing an issue in regards to escaping strings on the server side (using Node.js & Express.js) that contain greater/less than signs (<, >). Below is the code snippet I'm using on the server side: socket.on('message', fu ...

What steps can be taken to ensure that the design of this page flows seamlessly?

Interested in a design similar to this https://i.sstatic.net/wbXo2.jpg <!DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8> <title>Title</title> <style> html, body { height: 100%; margin: 0; ...

What is the best way to send an object key/value pair to a Vue template?

I've made progress on my component, but I'm facing an issue where the links are going to http://localhost:5173/[object%20Object]. It seems like I've reached a mental roadblock. This is what my component looks like: <template lang="p ...

Issues with Wordpress Ajax request on customized page are causing functionality to fail

Everything appears to be in order, but I am still unable to populate the destination. So far, I have confirmed that the PHP and JS files within my plugin are being located and can even generate output in XML. This is evident when observing the default beh ...

While loop not yielding immediate result with asynchronous function

As a beginner in Node.js, I have successfully connected an LCD Panel and a 4x4 Membrane matrix keypad to my Raspberry Pi. Using Node.js, I have programmed them to work together. My goal is to have the LCD panel immediately display any key pressed on the ke ...

CSS documents are being displayed as type text/plain

My goal is to host my static blog (built with Jekyll) on my Ubuntu server, but I'm encountering a problem where the CSS isn't being applied and I keep seeing this error: "Resource interpreted as Stylesheet but transferred with MIME type text/pla ...

Trouble with CSS positioned image rendering in Internet Explorer? Z-index not solving the issue?

I've been working on a timeline project where the completed sections should have a green background with a check mark image in the foreground. It appears correctly in Firefox, Chrome, and Safari. However, in IE 7 and 8 (and possibly 9), the layout is ...

The function causes changes to an object parameter once it has been executed

I've encountered an issue with a function that is supposed to generate a string value from an object argument. When I call this function and then try to use the argument in another function, it seems to be getting changed somehow. Here is the code fo ...

Process the HTML content in PHP only after it has finished loading

When attempting to parse an HTML page using PHP with DOMDocument, I encountered an issue where a javascript on the page was updating an element after the DOMDocument loaded the page. This resulted in parsing the HTML before the elements were fully update ...

Issues with incorrect source path in Typescript, Gulp, and Sourcemaps configuration

In my nodejs app, the folder structure is as follows: project |-- src/ | |-- controllers/ | | |`-- authorize-controller.ts | |`-- index.ts |--dist/ | |--controllers/ | | |`-- authorize-controller.js | | |`-- authorize-controller.js.map | ...

Accessing PHP parameters in JSP files can be accomplished by utilizing specific

The PHP code snippet below checks for a username and password match before redirecting to a JSP page. if($userName==$dbUserName&&md5($passWord)==$dbPassWord){ echo "<input name='username' type='hidden' value='$userN ...

Enhance your WooCommerce shopping experience by incorporating a variety of personalized checkout fields organized into two distinct

I have implemented custom code to create unique checkout fields based on the number of products in a customer's cart. Each product requires 4 customized checkout fields, displayed in two columns side by side. The expected result is as follows: co ...

The post page remains out of reach for Ajax

I've been struggling for hours to identify the issue with this code. I realized that I am unable to access the updateuser.php file even though it is in the same directory and the filenames are correct. Can someone please review the code below and let ...

What is the correct method for redefining properties and functions in Vue.js?

Is there a proper method for overriding methods using mixins in Vue.js? While it's possible to mimic inheritance with mixins, what if you only want to extend certain props without completely replacing the entire prop value? For example, let's sa ...

Is transforming lengthy code into a function the way to go?

I have successfully implemented this code on my page without any errors, but I am wondering if there is a more concise way to achieve the same result. Currently, there is a lot of repeated code with only minor changes in class names. Is it possible to sh ...

Incorporate content from a single HTML file into a different one

Hello, I am working with two HTML documents - let's call them index.html and index2.html for this example. I am looking to embed all the code within the body tag of index2.html into a section within index.html. Is there a way to create this connectio ...

What is the reason for function expressions being hoisted when called within Express JS middleware?

It's common knowledge that function declarations are hoisted, allowing them to be called from anywhere in your script. However, this is not the case for function expressions. For instance: test(); const test = () => { console.log(1+3); } ...

Transforming HTML content in real-time using Express.js

I'm a little uncertain if I understand the concept of Express MVC correctly: If my goal is to create a single page application and dynamically modify the HTML, can Express assist me with this? Or will I only be able to work with static pages that req ...

Achieving consistent hover effects in both Firefox and Chrome with CSS

Currently, I am faced with a dilemma regarding some CSS hover effects and table formatting. Despite successfully implementing most aspects of the design, there is an issue with how different browsers interpret padding within elements during color changes o ...

How can you prevent a draggable element from surpassing the bottom of the screen?

I'm dealing with an element that I want to make draggable only along the Y-axis. It needs to be able to go past the top of the screen, but I need to restrict it from going past the bottom of the screen. I recently came across the containment feature i ...