Javascript Error: Missing Object (SelectedIndex Property)

Struggling to find a solution for the mysterious "Object Expected" error that keeps popping up. Currently working on a concert attendance form page where users input their information. The pesky error is showing up in my function "totalBill," specifically with the objects "city" and "dates."

  • Frustratingly, the error rears its head at j=dates.selectedIndex; and k=city.selectedIndex;
  • I'll provide snippets of code that I suspect are related to the issue.

This snippet shows part of the function:

<script language="JavaScript" type="text/javascript">
    var city2=" ";
    var date2=" ";
    function totalBill() {
        with (document.coldplay) {
            var j;
            var k;

            j = dates.selectedIndex;
            k = city.selectedIndex;

            if (dates.options[j].value == "1") {
                date2 = " Friday, June 5th";
            }
            if (dates.options[j].value == "2") {
                date2 = " Saturday, June 6th";
            }

            if (city.options[k].value == "Chicago") {
                city2 = " Chicago";
            }
            if (city.options[k].value == "Austin") {
                city2 = " Austin";
            }

In the form section of the body, the user selects the city and date:

    <select name="city">
        City:
        <option value= "Chicago"> Chicago, Illinois 
        <option value= "Austin"> Austin, Texas 
        <option value= "Miami"> Miami, Florida  
    </select><br>
</td>
<td>
    <select name="dates">
        Date:
        <option value= "1"> Friday, June 5th 
        <option value= "2"> Saturday, June 6th
        <option value= "3"> Friday, June 12th  
        <option value= "4"> Saturday, June 13th
        <option value= "5"> Friday, June 19th 
        <option value= "6"> Saturday, June 20th
        <option value= "7"> Friday, June 26th  
        <option value= "8"> Saturday, June 27th
    </select>

Answer №1

Retrieve the elements using document.getElementById("dates") and then access its property:

document.getElementById("dates").selectedIndex

Keep in mind that you must either include the id attribute or obtain the element through another method, such as by name.

update

Here, it is crucial to retrieve the element and then manipulate its properties. Adding only the id "dates" will suffice, but I suggest utilizing getElementById() [or jQuery equivalent] for better code clarity.

Answer №2

Check out this initial JavaScript code snippet:

var city2 = " ";
var date2 = " ";

function totalBill() {
  var date = document.getElementById("date");
  var date2 = date.options[date.selectedIndex].text;

  var city = document.getElementById("city");
  var city2 = city.options[city.selectedIndex].value;

  alert("City : " + city2 + "\nDate: " + date2);
}

function addListener() {
  document.getElementById("submit").addEventListener("click", totalBill);
}
<body onload='addListener()'>
  <table>
    <tr>
      <td>City:
        <select name="city" id="city">
          <option value="Chicago">Chicago, Illinois</option>
          <option value="Austin">Austin, Texas</option>
          <option value="Miami">Miami, Florida</option>
        </select>
      </td>
      <br>
      <td>Date:
        <select name="date" id="date">
          <option value="1">Friday, June 5th</option>
          <option value="2">Saturday, June 6th</option>
          <option value="3">Friday, June 12th</option>
          <option value="4">Saturday, June 13th</option>
          <option value="5">Friday, June 19th</option>
          <option value="6">Saturday, June 20th</option>
          <option value="7">Friday, June 26th</option>
          <option value="8">Saturday, June 27th</option>
        </select>
        <td/>
        <br>
    </tr>
  </table>
  <button id="submit">Calculate</button>
  </bod>

Answer №3

@BIU If the OP's code is placed within a form named "coldplay", it should function correctly. You can view an example at jsfiddle.net/mn8vzbv2/2 However, while this solution may work, it is advised to avoid using with. Using IDs may not be the best approach as there could be multiple dropdowns on the page. IDs are not ideal for reusable code – Juan Mendes

Absolutely right! Thank you, Juan, for resolving this issue. It was simply a typo in the form name! A small mistake like that can really throw things off track, huh! Thanks once again.

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

Place the token within the Nuxt auth-module

Working on a project using the Nuxt auth-module. The Login API response is structured like this: data:{ data:{ user:{ bio: null, createdAt: "2021-06-29T12:28:42.442Z", email: "<a href="/cdn- ...

What is the best way to extract HTML using selenium.webdriver in Python?

Appreciate your attention, and please excuse any errors in my English. I am currently attempting to retrieve HTML from . The process involves entering some text into an input box and clicking a button, which triggers the following actions: Load the Yaho ...

The POST method in Node JS request-promises does not properly handle string inputs

When I am trying to establish a connection between my node.js module and another server, I utilize the 'request-promise' library. My implementation for posting data looks like this: rp.({ method: 'POST', headers:{ 'Conte ...

Sharing data between React JS components Passing information between different components in React JS

My NavBar.js component contains login information for the logged-in user. It displays "Welcome" along with the user details when the user is logged in. Now, I want to replicate this functionality in the ProductList.js component so that when a user posts a ...

When using an HTML Select element with options loaded through Ajax, the desired item for selection is not being automatically selected

This is a strange situation. Collaborating with others and using sample code, I have created a routine that utilizes AJAX to pass a value from one select to a PHP file. The PHP file then generates a second select with options, each option designed to check ...

Angular5 causing all divs to have click events at once instead of individually triggered

I am a beginner when it comes to working with Angular and I have encountered an issue. I created a click event on a FAQ page in Angular 5, but the problem is that when I click on one FAQ, they all open up instead of just the targeted one. Here is my TypeS ...

Avoid executing top-level path middleware with app.use('/') in Express routing when directly accessing child or nested paths

Perhaps the title may not be as accurate as I hoped, but I have a very simple example to share. On my website, there are two main areas - a public area and a restricted admin area. example.com/admin (admin home page) example.com/admin/news (news page) ...

Tips for resolving the error message 'Object(...) is not a function' when using ref().set() with Firebase

While attempting to include custom information for a newly registered user in Firebase, I encountered an issue where the ref().set() function is being identified as not a valid function. What could be causing this problem? I have verified that the syntax ...

Use the jqwidgets jxGrid with the checkbox selection mode to enable row selection by checking for any clicks on the row

Currently, I am using a jqxGrid that contains checkboxes. I would like the ability for users to select a row by clicking on any part or column of the row, not just on the checkbox itself. Unfortunately, it seems this feature is not directly supported. Has ...

Due to high activity on the main thread, a delay of xxx ms occurred in processing the 'wheel' input event

While using Chrome version: Version 55.0.2883.75 beta (64-bit), along with material-ui (https://github.com/callemall/material-ui) version 0.16.5, and react+react-dom version 15.4.1, an interesting warning message popped up as I scrolled down the page with ...

Can JavaScript be used to retrieve time information from a central location?

In the process of developing a PhoneGap application, I am restricted to using only HTML, CSS, and JavaScript. I am seeking guidance on how to retrieve time information from a centralized server using strictly JavaScript. Is it possible to achieve this by ...

Click event triggers dynamic function call

Is it possible to have different functions for ng-click depending on the loaded controller page? <a ng-click="removeEvent(event)" class="top_menu_link"> REMOVE</a> For instance, if I want the same button to trigger a remove action but on diff ...

What is the best way to send my webform data to a web API controller as a model class using JQuery AJAX?

This is the AJAX code I have written to pass two values to my API: function submitData() { var username = $("#username").val(); var password = $("#password").val(); $.ajax({ type: 'POST', ...

What is the process for setting up a resthook trigger in Zapier?

I'm currently integrating Zapier into my Angular application, but I'm struggling with setting up a REST hook trigger in Zapier and using that URL within my app. I need to be able to call the REST hook URL every time a new customer is created and ...

Adding External JS Files to a Node.js Project

I recently discovered how to incorporate a JS file into Node JS. However, I am facing an issue with two JS files in particular - hashing.js and encoding.js. Within encoding.js, I have the following code: exports = exports || {}; exports.encoding = encodi ...

Is react-particles-js still compatible for me to integrate?

I recently discovered that the package found here: https://www.npmjs.com/package/react-particles-js has been deprecated. Can I still utilize this package? The codes in question can be viewed at: https://codesandbox.io/s/particle-js-background-forked-woypk ...

Utilize prop-types inheritance when a component is rendered via props

Is it possible to inherit prop-types when a component is rendered via the parents prop, without direct access to 'ChildProps' and 'Props' interface? Parent Component interface ChildProps { counter: number; setCounter: React.Dispat ...

Struggling with handling numbers and special symbols in the Letter Changes problem on Coderbyte

Hello I have been struggling to find a solution for my current issue. The problem lies within an exercise that requires changing only alphabetical characters, but test cases also include numbers and special characters which are being altered unintentionall ...

Implementing a document click event to reset timeouts using JQuery

I'm having trouble resetting a timeout timer every time there is a click interaction with the document. The clearTimeout function doesn't seem to be working as expected. Here is the jQuery code snippet: $(document).click(function(e){ $("#vidB ...

Tips for simulating difficult private attributes within a class during unit testing in TypeScript

Is there a way to mock the value of a hard private property in a unit test? For example, how can I expect something like expect(event.getEventHis()).toBeEqual(['a', 'b']) export class EventController { #event: []; constructor() { ...