Looking to establish a default variable value prior to running a select action in JavaScript?

As a new learner of JavaScript, I have managed to figure out how to retrieve values from my select drop down. However, one issue I am currently facing is displaying a default value when a user first visits the page, which then changes based on the selection made from the drop down menu. Right now, no value is displayed until an option is chosen from the drop down. Despite trying to search for a simple guide on how to achieve this, I have not been successful. Below is the code I am working with:

function val() {
   d = document.getElementById("select_year").value;
   document.getElementById("demo").innerHTML = d;
 }
<select onchange="val()"  id="select_year">
    <option selected value="2017">2017</option>
    <option value="2016">2016</option>
    <option value="2015">2015</option>
</select>

<p id="demo"></p>

Answer №1

It appears that all you need to do is call your function.

function grabValue() {
  let data = document.getElementById("select_year").value;
  document.getElementById("demo").innerHTML = data;
}

grabValue();
<select onchange="grabValue()" id="select_year">
        <option selected value="2017">2017</option>
        <option value="2016">2016</option>
        <option value="2015">2015</option>
  </select>

<p id="demo"></p>

Answer №2

Simply alter something slightly.

<option chosen="chosen" value="122"></option>

This adjustment should suffice.

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

What is the best way to ensure that my $.ajax POST call works seamlessly with SSL?

Below is the JavaScript code I am using: parameter = "name=" + name + "&email=" + email + "&phone=" + phone + "&comments=" + comments; $.ajax({ url: 'sendEmail.php?' + parameter, success: ...

The "util" module has been extracted to ensure compatibility with browsers. Trying to use "util.promisify" in client code is not possible

Currently, I'm in the process of scraping LinkedIn profiles with the help of this library: https://www.npmjs.com/package/@n-h-n/linkedin-profile-scraper. Listed below is the code snippet that I am using: <script> import { LinkedInProfileScraper ...

When the jquery is still running, HTML initiates the loading of a new page

When I click on an anchor HTML tag with a link, I want to change the value of a variable in jQuery. However, even though the tag loads a new page, the variable's value remains unchanged. After doing some research online, I discovered that this issue ...

Adapting npm scripts with Node.js based on the current context

Can you set up package.json to execute a different npm start script depending on the context? For instance, I want to run DEBUG=http nodemon app.js during development. However, I prefer to run node app.js in production. ...

Checking the formik field with an array of objects through Yup for validation

Here is a snippet of the code I'm working on: https://codesandbox.io/s/busy-bose-4qhoh?file=/src/App.tsx I am currently in the process of creating a form that will accept an array of objects called Criterion, which are of a specific type: export inte ...

Are there any other options besides using the React Material-UI makeStyles() function for styling class Components?

While experimenting with the makeStyles() function in Material-UI's React library, I encountered a specific error message: The use of hooks is limited to the body of a function component. Below is a snippet of the code that triggered this error: ...

To retrieve the request parameter within the socket.on operation

As a newcomer to node.js, I may have made some mistakes along the way. Please bear with me. When trying to retrieve parameters passed in the URL like localhost:3000?id=man&fm=gilli, I used the following code: app.get('/',function(req, re ...

Rails 4 experiences a strange phenomenon where Ajax is triggered twice, resulting in the replacement of

After reviewing other similar questions, it appears that the best approach is to wait for the initial Ajax request to complete before proceeding with the next one. I believed that the following code would handle this situation, but somehow the request is t ...

Leveraging JSON Data for Dynamic Web Content Display

I have been attempting to parse and display the JSON data that is returned from a REST API without any success. When tested locally, the API's URL structure is as follows: http://localhost/apiurl/get-data.php It returns data in the following format ...

Asynchronous JavaScript function within a loop fails to refresh the document object model (DOM) despite

I have been working on a function that utilizes ajax to retrieve instructions from a backend server while the page is loading. The ajax code I've written retrieves the instructions based on the number provided and displays them using the response.setT ...

What is the best method for inserting dynamic HTML content (DIV) with JavaScript?

Can someone assist me in dynamically adding HTML content when data is returned from the server-side? I am currently using ajax/jQuery to handle server-side processing requirements. The success code section of my ajax function allows me to write HTML elemen ...

Should I Change or Focus in jQuery? What event is best to use with a select dropdown in order to trigger a call to a jQuery-AJAX function?

I have a single select dropdown element in my HTML code: <select id="student" name="student" class="form-control"></select> I am looking to implement a jQuery-AJAX function that will populate the option values in the select dropdown above. H ...

Executing two nested loops with a delay in jQuery

I am currently working on a script that sends an ajax post to another page. I need to run two for loops before sending the ajax request with a timeout. The first loop is successful, but when I try to run the second loop, all requests are sent at the same ...

When the JavaScript string retrieved from the database is null, it will be displayed as an empty string

Currently, my Ajax setup involves querying a database on the server with SELECT someColumn FROM someTable. The returned value of someColumn is then updated on the client side by using $('#someElement').text(someColumn); Everything works perfectl ...

Incomplete JSON response being received

We set up an express server to call an API and successfully requested the JSON object in our server. However, we are facing an issue where the JSON data is getting cut off when being displayed as a complete object on the client side. We tried using parse i ...

Do we really need TypeScript project references when transpiling with Babel in an Electron project using Webpack?

Currently, I am in the process of setting up my project configuration and have not encountered any errors so far. However, based on my understanding of the Typescript documentation... It appears that Project references are not essential when using babel-l ...

Adjusting the dimensions of images by using the percentage width and height relative to the body

On my website, I am displaying two images that are hosted on another company's server. To ensure these images adjust with the size of the browser window, I have set their width and height as a percentage relative to the body. However, the issue arise ...

Single-page application powered by WordPress and universal JavaScript

Can a WordPress single-page application be created using isomorphic/universal JavaScript approaches (utilizing frameworks like React and Angular2)? ...

Having trouble with my JavaScript code in Visual Studio because of a bundler issue. It's throwing an Uncaught ReferenceError for trying to access a variable before initialization

My AJAX request looks like this: $.ajax({ method: 'GET', url: '/api/some-data', headers: { 'Content-Type': 'application/json' }, success: function(data) { if (data != null) { var userDat ...

Utilizing jQuery with live content to determine dimensions as required

Within my web application, I have a page that dynamically retrieves a view with both HTML and JavaScript. The JavaScript is responsible for rendering a chart into the retrieved view. The problem arises because the chart library I am utilizing (flot) necess ...