JavaScript function dysfunction caused by global variable fatality

While attempting to update a global array using JavaScript, I encountered an issue where I couldn't access anything about it within a function. Removing the if/else statement allowed the alert for new_time to work, but the final alert did not display. Unfortunately, including the if/else statement caused my code to malfunction, halting its execution altogether. Despite knowing that global variables can be accessed simply by their name, why does changed_select_box_array present challenges in this context? (I also attempted to reference it as global., window., and this.)

var one = document.optionObject("id_open_time_1");

var changed_select_box_array = [];

function showID(id){
    if (changed_select_box_array.length > 0){
        alert('somethin');
    }
    else{
        alert('nuttin');
    }
    var x = document.getElementById(id).selectedIndex;
    var time = document.getElementsByTagName("option")[x].value;
    var change = {id:id, new_time:time};

    alert(change.new_time);

    changed_select_box_array.push(change);
    alert(changed_select_box_array[0].id);
}

Interestingly, the snippet below (which had been innocuous for several days) seemed to be the cause of the problem:

    var one = document.optionObject("id_open_time_1");

I'm curious to understand why that particular line is causing issues.

Answer №1

Everything seems to be working fine on my end. No errors for me.

<select id="test">
    <option value="1">T1</option>
    <option value="2" selected>T2</option>
    <option value="3">T3</option>
</select>

<script>
var changed_select_box_array = [];
showID('test');

function showID(id){
    if (changed_select_box_array.length > 0){
        alert('something');
    }
    else{
        alert('nothing');
    }
    var x = document.getElementById(id).selectedIndex;
    var time = document.getElementsByTagName("option")[x].value;
    var change = {id:id, new_time:time};

    alert(change.new_time);

    changed_select_box_array.push(change);
    alert(changed_select_box_array[0].id);
}
</script>

JsFiddle

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

Utilizing Vue JS to showcase a pop-up block when hovering over a specific image

There are four images displayed, and when you hover over each one, different content appears. For example, hovering over the first image reveals a green block, while hovering over the second image reveals a blue block. However, the current logic in place i ...

Incorporate a distinct, unique value from a JSON dataset into each iteration of the .each statement

My code includes an each statement that looks like this: $.each(data, function(i, value) { sublayers.push({ sql: "SELECT " + firstSel2 + ", cartodb_id, the_geom_webmercator FROM full_data_for_testing_deid_2 where " + firstSel2 + "=&ap ...

Ways to modify the end result using callback information

In my scenario, I am working with an object that has keys id and name as shown below. The goal is to retrieve the customer name based on the id and then update the object accordingly. Const arr=[{id:1,name:''},{id:2,name:''}]; ...

Mastering the art of jQuery scrolling: A step-by-step guide

Is there a way to utilize jQuery for scrolling purposes? For example, transforming this: <ul class="nav navbar-nav navbar-right"> <li class="active"><a href="#home">Home <span class="sr-only">(current)</span></a> ...

Uniform distribution of resources across all nodes

I'm currently implementing navigation in my application using React BrowserHistory. I want all files to be served from my Node server regardless of the URL path being accessed. This is the code for my server: const http = require('http'); ...

Angular 4 or React: Unveiling the Performance Battle between Theory and Reality

While it may seem like the same old comparison between x vs y, what is faster?, I believe my version offers a unique perspective. React and Angular are as different as GTK and Qt (or even more), making comparisons between them futile - one is a versatile f ...

Activate dual AJAX JSON and cycle through multiple alerts each time an "ul li" element is clicked

In my code, I am utilizing two ajax requests. One retrieves a chat userlist column in JSON format, while the other fetches the message history for each user. The functionality works such that when a $('.member_list ul li') element is clicked, th ...

Converting from Async.js parallel to Bluebird: A Step-by-Step Guide

Utilizing async.js allows me to define promises with handlers, providing polymorphism and separating results. Can this be achieved in bluebird as well? async.parallel({ cityPromises: (cb)=>{ City.find({ ...

Error: No schema found for the specified "User" model

Attempting to establish a connection with the MongoDB database using Mongoose and defining the model resulted in the following error message: MissingSchemaError: Schema hasn't been registered for model "User" Several approaches were taken to address ...

Utilizing a JavaScript variable within a jQuery function as an attribute

var image = "path.png"; Is it possible to include the 'image' variable in the jQuery function like this? $('#mapfoto').prepend('<img id="theImg" src="http://path.gr/" + image />'); ...

Firestore is failing to accept incoming data when the setDoc method is employed

I am encountering an issue with my app's connectivity to the Firestore database when attempting to utilize setDoc. The database is successfully operational for next-auth, creating records as intended. However, the problem arises when trying to enable ...

Dealing with the validation of two forms on a single webpage: Strategies and Solutions

In a popup, there are two forms that alternate display - one for editing (loaded via ajax) and one for creation. Using jQuery validation, I aim to show hints for both editing and field submission. The validation includes ensuring time spans do not overla ...

What is the best way to insert a button at the end of the last row in the first column and also at the

I am working on a JavaScript project that involves creating a table. My goal is to dynamically add buttons after the last row of the first column and also at the top of the last column. for (var i = 0; i < responseData.length; i++) { fo ...

AngularJS's ng-model is able to handle dynamic changes effortlessly

I am working with an array of objects that can be viewed https://i.sstatic.net/Fg1L8.png Within the dropdown box, I have names listed and a text box that displays the value from the selected object https://i.sstatic.net/rY0ET.png The input box is current ...

Ember's distinctive feature: Named Block Helpers

Can we create "named blocks" in a different way? For instance, {{#customBlock "repeatableBlock"}} {{!-- block containing numerous properties and data that may become messy if hardcoded multiple times --}} {{/customBlock}} Then, elsewhere in the code, {{ ...

What is the most effective way to save and access British pound symbols?

Every so often, I face this issue where I end up resorting to a messy workaround. There must be a correct way to handle it though, as it's common to work with UK pound symbols. The dilemma is this: when the user inputs a UK pound symbol (£) into a t ...

Steps for including a header and footer with page numbers in an HTML page without disrupting the rest of the content when printing

When I print a page with a table that spans multiple pages, I want to ensure that my header and footer are included on every page. The code I've tried so far has treated the entire content as one continuous page. How can I achieve this? ...

best way to eliminate empty p tags and non-breaking spaces from html code in react-native

How can I clean up dynamic HTML content by removing empty <p> tags and &nbsp? The whitespace they create is unwanted and I want to get rid of it. Here's the HTML content retrieved from an API response. I'm using the react-native-render ...

Incorporating HTML themes within ReactJS

While I am still relatively new to ReactJS, I am eager to expand my understanding of it with this question. I have a preexisting HTML/CSS theme that I would like to integrate into a React application. Is there a method to incorporate this theme seamlessly ...

Navigate through a list of data in JSON format

After successfully implementing a jQuery AJAX call, I encountered difficulty in parsing the returned value. Working with a MySQL database, I am returning a PHP array() to my jQuery AJAX function using echo json_encode($reservationArray); Upon appending th ...