Tips on how to prevent altering the formula selection following the onchange event

Hey there, I'm facing an issue with JavaScript.

Please check out my website . What I want is that when I select "Option One", even after reloading the website, it should stay selected as "Option One" and not revert back to "Select...".

Any ideas on how to achieve this?

Thanks!

EDIT: Here's my PHP script:

<?php
if (isset($_POST['mySelect']))
{
    $value = $_POST['mySelect'];
    if ($value == 1) {
        echo "blabla";
    }
    elseif ($value == 2) {
        echo "hello";
    }
}

Answer №1

To achieve the desired outcome, you have two options:

<?php
if (isset($_POST['mySelect']))
{
    $value = $_POST['mySelect'];
echo "<script>$('select option[value=\"".$value."\"]').attr('selected', 'selected');</script>";
    if ($value == 1) {
        echo "blabla";
    }
    elseif ($value == 2) {
        echo "hello";
    }
} ?>

Alternatively, you can modify the HTML directly and eliminate the need for JavaScript:

<?php
if (isset($_POST['mySelect']))
{
    $value = $_POST['mySelect'];
    if ($value == 1) {
        echo "blabla";
    }
    elseif ($value == 2) {
        echo "hello";
    }
} ?>
<select id="mySelect" name="mySelect" onchange="document.getElementById('myForm').submit();">
        <option value="" selected="selected">Select...</option>
        <option value="1" <?php if($value == "1") echo "selected"; ?>>Option One</option>
        <option value="2" <?php if($value == "2") echo "selected"; ?>>Option Two</option>
</select>

Answer №2

To achieve the desired result, it is important to use PHP to specify the selected option.

<select id="mySelect" name="mySelect" onchange="document.getElementById('myForm').submit();">
        <option value="" selected="selected">Select...</option>
        <?php
        $selected1 = ($value==1)?"selected":"";
        $selected2 = ($value==2)?"selected":"";
        echo '<option value="1" '. $selected1 . ' >Option One</option>';
        echo '<option value="2" ' . $selected2 . ' >Option Two</option>';
        ?>
</select>

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 you use jQuery to remove a class from an element after a specified period of time?

After updating a record in the database, I plan to make modifications using an AJAX request. Once that is done, I will dynamically add a class to the rendered div by utilizing the addClass method. The class being added (we'll refer to it as colored) c ...

The behavior of React Router varies between local development on localhost and deployment on Heroku

Currently in the process of constructing a React-based website, initiated with create-react-app and incorporating react-router-dom`. The setup is as follows: index.js import React from 'react'; import ReactDOM from 'react-dom'; impor ...

`Where can I locate a grid example?`

Right here: Upon reading the documentation, I discovered: onItemInserting has the following arguments: { grid // represents the grid instance item // item being inserted } In my software application there are multi ...

Automatically reloading POST request when browser back button is pressed

Our web application is built on Spring MVC and Thymeleaf. When a user lands on the home page with a GET request, they enter 2 parameters and submit a POST request. After successful submission, they are directed to another page (let's call it page2) wi ...

Issue with Ajax Call preventing animation in Google Chart Gauge on Google API

setInterval(function () { refreshGauge(); }, 5000); var chart1 = null; function refreshGauge() { $.ajax({ type: "POST", url: "Default.aspx/GetGuageData", data: '{}', contentType: ...

Exploring the process of sending props via the render method in Vue.js and observing their behavior

Struggling with passing a prop from a parent component down to a child created using CreateElement/render in vue.js and then watching it. Here is the parent component: Vue.component('my-drawing', MyDrawing) new Vue({ el: '#drawing' ...

Neglecting to pass data to the controller through the onclick function

Using this specific button element in my JavaScript implementation has raised some concerns. <button id="bid" type="button" class="button" onclick="connect()">Save</button> While I have noticed that it displays an alert message when 'ale ...

Ways to incorporate External JS and CSS files into Angular 5 (loading files with a delay)

I have encountered some challenges while attempting to import external JS and CSS files into my Angular 5 application. Below is the code snippet that I have tried so far: Component.ts : ngOnInit() { this.loadScript(); // also attempted with ...

Trouble reading property 'map' in a react-redux todo application

Greetings! I am currently in the process of developing a to-do list application, but I have encountered the following error: TypeError: Cannot read property 'map' of undefined Below is the code snippet where the error occurs: 4 | function T ...

Effective strategies for efficiently managing a multitude of key codes within an event handler?

This might lean towards a pure JS question, but I'm including Angular2 as well in case any developers with Angular expertise have alternative techniques for this While developing an angular2 application, I'm implementing a keydown event handler ...

I want my website to display tech bargains in a unique way - whenever I showcase 9 items, the next item I add will automatically show up below the ninth product rather than

I've been working on a website that showcases tech deals, and I've encountered an issue where if I insert a product after the ninth one, it doesn't align properly. Instead of appearing to the left of the ninth product, it displays below it. ...

Iterate through a JavaScript array to access objects with varying IDs

Struggling to navigate the JSON data due to ID 29450 and 3000 out of a total of 1500 IDs in the database. Looking to log the information ['Id', 'Description', 'StartDate'] for both IDs. Feeling a bit stuck, hoping someone can ...

An error was encountered involving an unexpected token < at the beginning of a JSON file while using express with firebase

After setting up an authentication system in express using firebase auth, I established an endpoint in my express server: app.post('/users/login', (req, res) => { console.log('logging in...'); firebase.auth().signInWithEmail ...

What's preventing me from using just one comparison condition in TypeScript?

The issue at hand is quite simple: An error occurred because I tried to compare a number with a 'Ref<number>' object. It seems ridiculous that I can't compare two numbers, but as I am new to Typescript, I would greatly appreciate some ...

Barba.jS is causing a delay in loading scripts after the page transition

One of my index files includes Gsap and Barba JS, while an inner page includes additional JS files such as locomotive.js and OWLcarousel.js. These two JS files are not necessary for the index page. However, when transitioning from the index page to the inn ...

Do I actually have to reiterate all these requirements in each route module file?

As I work on developing a more extensive web application, I have come to realize the importance of modularizing my routes into separate files. However, in doing so, I've noticed that I end up duplicating a lot of required modules. Prior to moving the ...

Next.js encountering page not found error due to broken link URL

Currently, I am working on implementing a login system in next.js. In the login page, I have included a Link to the Register page using the Link href attribute. However, every time I click on that link, it displays a message saying "404 page not found." Al ...

Why does tween animation appear instant rather than smooth?

I am trying to achieve a camera movement effect where the camera transitions from its current position to the center of a mesh (which is a sphere and I want to be inside of it) when a button is clicked. I have implemented a function with a tween for this ...

Changing text inside ion-header-bar directive

When utilizing the ion-header-bar directive, I have the left side designated as class="button", the middle section containing <h1> with the word "Recent", and the right side as <ng-icon>. The text on the left side is dynamically generated usin ...

Tips for Configuring a Nestjs Query Using TypeORM to Retrieve Several Entries

When I send this specific URL from my Angular application: http://localhost:3000/api/skills?category_id=2 The main issue revolves around how to modify the code in order to successfully retrieve all skills with a category_id of 2. It is important to note ...