Having trouble accessing the value of null and adding it to an array

Having trouble with a 'value' of null error that is not getting resolved even after window.onload = function(){

Any suggestions on what to do? Here's the code snippet:

window.onload = function(){
        var shashank = document.getElementById('shashank').value;
        var kiran = document.getElementById('kiran').value;
        var sumanth = document.getElementById('sumanth').value;
        var arun = document.getElementById('arun').value;

var arr = [shashank,kiran,sumanth,arun];

document.getElementById('btn').addEventListener('click', showName);
}

This is the html structure being used:

<html>
    <head>
        <title>Attendance Sheet</title>
        <script src="app.js"></script>
        <style>
            #present{
                width:50px;
                height:50px;
            }
        </style>
    </head>
    <body>
        <select>
          <option value="shashank">Shashank</option>
          <option value="kiran">Kiran</option>
          <option value="sumanth">Sumanth</option>
          <option value="arun">Arun</option>
        </select>
            <button id="present">P</button>
        <button id="btn">Submit</button>
    </body>
</html>

Answer №1

The reason for this issue is that you are attempting to retrieve an element that does not have an ID. Take a moment to review the MDN official documentation for getElementByID to better understand this concept. You can also refer to the corrected example on CodePen

<option id="shashank" value="shashank">Shashank</option>
<option id="kiran" value="kiran">Kiran</option>
<option id="sumanth" value="sumanth">Sumanth</option>
<option id="arun" value="arun">Arun</option>

Answer №2

In order to properly update your HTML, make sure to include unique IDs for elements like this:

<option id="unique-id" value="unique-value">Unique Option</option>

Alternatively, you can retrieve an array of all options using the following code:

let options = document.getElementsByTagName("option");

Answer №3

It appears that your <option> tags do not have the necessary ids for access. Furthermore, the approach you are taking may not be the most efficient, especially when dealing with a select element containing a large number of options. A better solution would be to utilize an event listener for the select element to only capture the selected option.

window.onload = function(){
  document.getElementById('btn').addEventListener('click', showName);

  var myOpt = document.getElementById('mySelect').value; // myOpt = shashank

  document.getElementById('mySelect').addEventListener('change', function(ev) {       
    // Save the selected option here for further processing
    myOpt = ev.target.value
  });
}

Don't forget to include the id mySelect in your <select> tag!

<html>
    <head>
        <title>Attendance Sheet</title>
        <script src="app.js"></script>
        <style>
            #present{
                width:50px;
                height:50px;
            }
        </style>
    </head>
    <body>
        <select id="mySelect">
          <option id="shashank" value="shashank">Shashank</option>
          <option id="kiran" value="kiran">Kiran</option>
          <option id="sumanth" value="sumanth">Sumanth</option>
          <option id="arun" value="arun">Arun</option>
        </select>
        <button id="present">P</button>
        <button id="btn">Submit</button>
    </body>
</html>

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 causes the component to remount with every update to its state?

PLEASE NOTE: Before posting this question, I realized that there were some errors in my code. I understand now that this question may not be helpful to others as it contains misleading information. I apologize and appreciate those who took the time to res ...

The appearance of the circle in Safari is rough and lacks smoothness

My circle animation works perfectly on Google Chrome, but when I switch to Safari the edges appear faded and blurry. I tried adding "webkit" to fix it, but had no luck. Is there a compatibility issue with Safari and CSS animations? Here is my code: Snapsh ...

Having trouble installing $ npm i mini-css-extract-plugin. Any ideas on what might be causing the issue?

There seems to be an error in my setup. I am using Visual Studio Code with gitBash. $ npm i mini-css-extract-plugin npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-p ...

Vue JS encountering Slack API CORS issue while using axios

I am currently developing an application using Capacitor JS & Nuxt JS to interact with the Slack API for setting my Slack status. I have successfully created a Slack App and obtained a xoxp- token, which works perfectly when sending a POST request via Post ...

The function responsiveTable does not exist

I recently added the following code to my aspx page: <script src="../Scripts/jquery.responsivetable.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#grdStudent').responsiveTable( ...

AngularJs fails to apply style to dynamic content in IE8 when using HTML5

Currently, I am in the process of developing a website with AngularJs and utilizing numerous JS scripts to address compatibility issues with Internet Explorer. I have organized the data in JSON format, and each page is designed to fetch and display differ ...

Safari on iOS9 is inaccurately calculating the total sum

My code involves calculating the sum of key/value pairs in a hash within a loop. I have noticed that there is a discrepancy in how the sum is calculated on ios9 Safari compared to other platforms. While I can address this issue for this specific scenario, ...

50% greater than the highest of the other values

I'm a beginner when it comes to JavaScript and I need help setting a maximum value of 50% of the selling price. Can someone offer guidance? The fields I have are called "sale_price" and "discount". click here for image description What is the best ...

Discover the size of an image using JavaScript by accessing innerHTML

I'm currently working on a unique AJAX function that retrieves image URLs without using node append for insertion. Instead, I opted to utilize innerHTML, but this has posed challenges in accurately obtaining the file dimensions. My current approach i ...

Why is the defaultDate property not functioning properly in Material-UI's <DatePicker/> component with ReactJS?

I recently implemented the <DatePicker/> component from Material-UI ( http://www.material-ui.com/#/components/date-picker ) in my project. I encountered an issue while trying to set the defaultDate property to the current date on my computer, as it r ...

Having trouble rendering a dynamic table with JavaScript utilizing a JSON object

I am struggling to retrieve data in JSON format and display it in a table. Despite trying various methods, I have been unable to make it work. Below is the code for this function. Can someone please assist me in identifying what is wrong with it? As of now ...

Is there a way for me to divide the data in a JSON file and display user tags in place of their IDs?

Looking to create a list admins command for a bot, I'm facing challenges in converting user ids to tags within the command. Take a look at what I have accomplished so far: const { MessageEmbed } = require('discord.js'); const { readFileSync, ...

Eliminate Bootstrap's validation glyphs

Issue Description I am attempting to eliminate the validation icons from Bootstrap, such as the "x" and "check" symbols. Despite my efforts to search thoroughly, I have been unable to locate where these icons are located in the code. Code Sample You can ...

I possess a webpage containing a div element that is loaded dynamically through ajax

One issue I'm facing is with a page containing a div that gets loaded via ajax when a button is clicked. The problem arises when a user tries to refresh the page by pressing F5, as the content of the div gets lost! Is there a way to ensure that when ...

Is there a way to execute publish without automatically triggering postpublish?

I am working on a project that includes a specific postpublish action in its package.json. Recently, I encountered a situation where I need to run the publish command without triggering the associated postpublish action. Is there a foolproof method to exe ...

Detecting changes in a readonly input in Angular 4

Here is a code snippet where I have a readonly input field. I am attempting to change the value of this readonly input from a TypeScript file, however, I am encountering difficulty in detecting any changes from any function. See the example below: <inp ...

Issue: Unable to 'locate' or 'access' ./lib/React folder while utilizing webpack

I've been delving into the world of React for a while now and decided to experiment with integrating it with webpack. Below is my webpack.config.js : var path = require('path'); module.exports = { entry: './app.js', outp ...

Troubleshooting slow/delayed performance when using manual dataItem.set() in Kendo UI Grid

I recently implemented an editable Kendo Grid with a checkbox column to toggle a boolean value, thanks to an ingenious solution offered by OnaBai. The implementation works flawlessly! The only issue I'm facing is that there seems to be a delay in cha ...

Displaying adornments in a vertical arrangement within a TextField using Material UI

Is there a way to display adornments vertically in a Material UI Textfield? I've been trying but it always shows up horizontally. Snippet: <TextField variant="filled" fullWidth multiline rowsMax={7} onFocus={() => h ...

Receiving a notification when attempting to log in with incorrect credentials

I am currently working on an Angular login page implementation using a username and password setup. When the user enters incorrect credentials, I want to display an alert message indicating the same. Here is the HTML code snippet for the form: <form [f ...