Tips for setting and modifying the default selection using JavaScript?

Programming Dilemma

In my HTML, there is a form structured like this:

<label for="alternativeGraph">Alternative graphs could be seen here:</label>
         <select id="selGraph" onchange="graphUpdate()" aria-label="Graph">
                <option value="1" selected="selected">Graph 1 (default)</option>
                <option value="2">Graph 2</option>
                <option value="3">Graph 3</option>
                <option value="4">Graph 4</option>
                <option value="5">Graph 5</option>
            </select>
      <button type="button" onclick="setDefault()"> Change default graph</button>

The aim is to have Graph 1 load as the default on page load and allow users to change the default graph using the setDefault() function. Here's the JavaScript involved:

function render(filename) {
fetch(filename).then(response  => response.text()).then(textAsString => 
     renderString(textAsString));
}

   
function graphUpdate(){
    let value = document.querySelector('#selGraph');
    let graph = ["graph_1.gv", "graph_2.gv", "graph_3.gv", "graph_4.gv", "graph_5.gv"]
    render(graph[value.selectedIndex]);
    
}

// function setDefault(){ # I am not sure about what should be added here...
//     let new_default_graph = document.querySelector("#selGraph");
//     new_default_graph.value = 
    

// }

Challenges Faced

The primary issue encountered is that upon website loading, despite choosing Graph 1 ("graph_1.gv" file) as the default, it does not display until clicking the dropdown menu. Other graphs are loaded correctly.

Inquiries:

Is there a method to pre-load the graph based on the initial selection? Additionally, how can the setDefault() function be modified so that when users select an option like 3, the website remembers this choice as the default upon refreshing?

Answer №1

For optimal performance, consider adding a window.onload event handler in your script to trigger the graphUpdate() function after all DOM components have finished loading:

window.onload = graphUpdate;

For saving the selected value persistently in the browser, you can utilize window.localStorage. Modify the event function like this:

window.onload = function() {
  let selected = window.localStorage.getItem('selectedGraph') || 1;
  document.querySelector('#selGraph').selectedIndex = selected;
  graphUpdate();
}

Don't forget to update the graphUpdate function to save the selected value:

function graphUpdate(){
    let value = document.querySelector('#selGraph');
    let graph = ["graph_1.gv", "graph_2.gv", "graph_3.gv", "graph_4.gv", "graph_5.gv"]
    render(graph[value.selectedIndex]);
    window.localStorage.setItem('selectedGraph', value.selectedIndex)
}

Additional information on window.localStorage can be found here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Answer №2

If your JavaScript code is executed after the document elements are loaded (by placing the <script> tag after them or using defer), you can simply run the graphUpdate() function.

To store default options, I recommend utilizing localStorage.

Avoid using attribute-based event listeners like onchange and onclick.

<label for="alternativeGraph">Alternative graphs could be seen here:</label>
<select id="selGraph" aria-label="Graph">
  <!-- values are easier to work with than indexes -->
  <option value="graph_1.gv">Graph 1</option>
  <option value="graph_2.gv">Graph 2</option>
  <option value="graph_3.gv">Graph 3</option>
  <option value="graph_4.gv">Graph 4</option>
  <option value="graph_5.gv">Graph 5</option>
</select>
<button type="button" id="setDefaultGraphBtn">Change default graph</button>
// Constants
const DEFAULT_GRAPH_KEY = "default-graph";
const DEFAULT_GRAPH = "graph_1.gv";

// Elements
const graphSelect = document.getElementById("selGraph");
const btn = document.getElementById("setDefaultGraphBtn");

// Functions
const render = async (filename) => {
  const res = await fetch(filename);
  if (!res.ok) {
    throw new Error(`${filename}: ${res.status} ${res.statusText}`);
  }

  renderString(await res.text());
};

const graphUpdate = () => {
  render(graphSelect.value);
};

const setDefaultGraph = () => {
  const val = graphSelect.value;
  localStorage.setItem(DEFAULT_GRAPH_KEY, val);
  graphSelect.querySelectorAll("option").forEach((opt) => {
    // remove any previous "default" text
    opt.textContent = opt.textContent.replace(" (default)", "");
    // add "default" text
    if (opt.value === val) {
      opt.textContent += " (default)";
    }
  });
};

// Bind event listeners
graphSelect.addEventListener("change", graphUpdate);
btn.addEventListener("click", setDefaultGraph);

// Get localStorage value or default
const defaultGraph = localStorage.getItem(DEFAULT_GRAPH_KEY) ?? DEFAULT_GRAPH;

// set default selected
graphSelect.value = defaultGraph;

// Now run functions to initialise
setDefaultGraph();
graphUpdate();

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

Having trouble deciphering this snippet of Express JS source code

Upon reviewing the Express JS source code, I came across the main module where express is being exported. module.exports = createApplication; function createApplication() { var app = function(req, res, next) { app.handle(req, res, next); }; m ...

Conceal the export capabilities and pagination of DataTables

Using the DataTables jQuery plugin, I have successfully integrated CSV and PDF export features. In addition, there is a form with three select options that display tables based on user selection. When a user chooses the second option from the list, it swi ...

Move to the following array when clicking PHP (using Ajax, perhaps?)

How can I trigger php code when a button is clicked? (I understand the distinction between client-side and server-side. However, I believe I have encountered a similar scenario before.) Consider the following array : $test_id = [ 1 => '15 ...

Error: Attempted to search for 'height' using the 'in' operator in an undefined variable

I came across the following code snippet: $('.p1').click(function(){ var num = 10; var count = 0; var intv = setInterval(anim,800); function anim(){ count++; num--; ...

Encountering a 404 error while attempting to retrieve data from Node.js within a React.js application despite the server being operational

This is my first time delving into the world of back-end development, and it's quite challenging for me. The tech stack I'm using includes React.js, Node.js, express.js, and mysql. However, when I try to fetch the result of a query, I keep runnin ...

Sort values depending on the value of another key

I have a list of different types: const types = ['BAKERY', 'FRUITS', 'RESTAURANT', ...]; The length of this array is not fixed. Additionally, I also have a corresponding category list for each type as shown below: const categ ...

Position Element on Top of Input Field

I'm struggling to position the Avatar element over my TextInput to create a traditional search bar appearance. However, the icon isn't overlapping the TextInput. Could you please explain why it's not working or suggest a more effective way t ...

There seems to be an issue with the Axios Post not consistently finishing each time

I'm a newcomer to React and running into some issues. Here is the API call I am currently using. Axios.post(Addr_currentRound_addOne, { gameId: gameId }).then(history.push("/leiter_tunierplan/"+gameId)); And here is the corresponding API c ...

Binding data to custom components in Angular allows for a more flexible

In my current scenario, I am looking to pass a portion of a complex object to an Angular component. <app-component [set]="data.set"></app-component> I want the 'data.set' object in the parent class to always mirror the 'set&apo ...

Transform javascript classes into flash

Is there a way to transform a JavaScript class into Flash and implement it the same way as the original one? For example: var MyClass = function() { var exports = {}; var message = exports.message = function showMessage(msg) alert(msg); ...

Is there a way to compact this code so that I don't need to repeatedly type it out?

I keep duplicating this block of code. Is there a more efficient way to simplify this code without repeating it? router.get('/reports', async (req, res) => { let filters = {}; ['y', 't', 's', 'r', ...

value assigned to ng-model does not update beyond its scope

My issue involves binding an ng-model to an input field. Despite this, the value of the variable it is connected to does not update outside of the specific div where the directive is defined: <div input-field ng-if="startTypes.selected.value == &a ...

Tips for integrating AudioControl with Phonegap

I couldn't find a suitable plugin, so I decided to create my own. My goal is to activate silent mode using a JavaScript command, however, I am encountering an error with the undefined method getSystemService. It seems like there may be a problem with ...

What is the reason behind AngularJS recognizing the $index directive and not the $parent directive?

I have been working on this up until now. Check out my code here. I'm trying to access $parent.$index in a directive, is that possible? Can someone explain it to me? <ul> <li ng-repeat="item in lists"> {{item.name}} ...

How to properly handle date property in a document when deserializing with Node.js

I am encountering an issue with saving documents in Couchbase that contain JavaScript Date values. I want to retrieve these values exactly as they are, without getting them back as strings like '2016-01-02T12:13:14Z'. After some research, I disc ...

Issue: A child component's function is unable to update the state of the parent component

I have been working on a project using React. Below is the code for the parent component: class Parent extends Component { constructor(props) { super(props); this.state = { deleteConfirm: false }; } onDelete = pass => { thi ...

Instead of receiving my custom JSON error message, Express is showing the server's default HTML error page when returning errors

I have set up a REST api on an Express server, with a React app for the front-end. The design includes sending JSON to the front-end in case of errors, which can be used to display error messages such as modals on the client side. Below is an example from ...

Generating fresh object instances and adding them to an array using vanilla JavaScript

I'm currently working on a form that should generate a new object with the input values upon submission, and then add that object to an array. However, I've noticed that the array seems to be "resetting" itself and not retaining the saved object ...

Enhancing the functionality of hidden input fields using jQuery

I'm looking to dynamically update the value of a hidden input element when a button is clicked. Here's what I have so far: Hidden Input Element: <input type="hidden" value="action" id="action" /> Buttons: <INPUT name=submit value=~#S ...

Encountering difficulties in creating an app with Apache Cordova

After setting up the proxy settings, I attempted to create a new app named "hello" using Cordova with the following commands: npm config set proxy http://proxy.company.com:8080 npm config set https-proxy http://proxy.company.com:8080 The creation comman ...