JavaScript is failing to add items to an array

Attempting to add coordinates and user-specified data from a form to an array named "seatsArray". Here's the code snippet:

<div>
<img onLoad="shiftzoom.add(this,{showcoords:true,relativecoords:true,zoom:100});" id="image" src="plan1.bmp" width="1024" height="768">
</div>

<script type="text/javascript">
var seatsArray = [];
</script>
<br><input id="backnave" type="radio" name="area" value="backnave" /> Back Nave<br>
<input id="frontnave" type="radio" name="area" value="frontnave" /> Front nave<br>
<input id="middlenave" type="radio" name="area" value="middlenave" /> Middle nave<br>
<input type="radio" id="standardseat" name="seat" /><label for="radio1">Standard</label><br>
<input type="radio" id="wheelchairseat" name="seat" checked="checked" /><label for="radio2">Wheelchair</label><br>
<form id="my_form" action="savetext.aspx" method="post" onsubmit="return prepare()">
  <input type="text" id="file_name" name="file_name" rows="1" cols="20" />
  <input type="hidden" name="seatsArray" />
  <input type="submit" value="Save" />
</form>

<form id="my_form" action="savetext.aspx" method="post" onsubmit="return prepare()">
  <input type="text" id="file_name" name="file_name" rows="1" cols="20" />
  <input type="hidden" name="seatsArray" />
  <input type="submit" value="Save" />
</form>

<script type="text/javascript">
function prepare();
{
  document.getElementById('seatsArray').value = seatsArray.join();
  return true;
}
</script>

<script type="text/javascript">
var coordinates = document.getElementById("image");
coordinates.onclick = function(e) {
e = e || window.event;

if (e && e.pageX && e.pageX) {
            e.posX = e.pageX;
            e.posY = e.pageY;

        } else if (e && e.clientX && e.clientY) {
            var scr     = {x:0,y:0},
                object  = e.srcElement || e.target;
            //legendary get scrolled
            for (;object.parentNode;object = object.parentNode) {
                scr['x'] += object.scrollLeft;
                scr['y'] += object.scrollTop;
            } 
            e.posX = e.clientX + scr.x;
            e.posY = e.clientY + scr.y;
        } 

var desc = "";
if(document.getElementByID("backnave").checked) {
  desc = "BN, "+desc;
} else if(document.getElementByID("middlenave").checked) {
  desc = "MN, "+desc;
} else if(document.getElementByID("frontnave").checked) {
  desc = "FN, "+desc;
}

if(document.getElementById('wheelchairseat').checked) {
  //Wheelchair seat is checked
  desc = "Wheelchair "+desc;
}

seatsArray.push(desc + e.posX, e.posY);

}
</script>

No data seems to be added to the array. This conclusion is drawn from the following ASP.NET code used to write the array contents to a text file:

<script runat="server">
    protected void Page_Load(object sender, EventArgs e) 
    {
        string path = Server.MapPath(".")+"/"+Request.Form["file_name"] + ".txt";
        if (!File.Exists(path)) 
        {
            using (StreamWriter sw = File.CreateText(path)) 
            {
                sw.WriteLine(Request.Form["seatsArray"]);
                sw.WriteLine("");
            }   
        }

        using (StreamReader sr = File.OpenText(path)) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                Response.Write(s);
            }
        }
    }
</script>

The filename matches what the user entered in the form under "file_name". I've set up seatsArray as a hidden form element so that it can be accessed via ASP.NET.

Is there an issue with the JavaScript order or something else causing the array not to populate? Any insights would be appreciated!

Thank you!

Answer №1

When using the browser, always remember to check for javascript errors. Firefox and IE are known to report 2 specific errors.

If you encounter a semicolon that shouldn't be there, it might cause issues with functions like prepare();

In cases where document.getElementById("image"); returns null, it can lead to failures with coordinates.onclick.

To effectively debug your code, I strongly recommend using tools such as Firebug in Firefox or developer tools in IE8 (you can access them by pressing F12).

One important tip is to declare seatsArray as an array before using it to avoid any unexpected errors.

<script type="text/javascript">

Insert this line: seatsArray = [];

function prepare() {

....

Answer №2

To troubleshoot the issue, consider inserting a couple of alert(seatsArray) commands in the JavaScript code before and after the points where you expect the values to change, as well as right before the form is submitted. If the expected values are displayed correctly, it indicates that the problem lies with the back-end system.

Upon closer examination: the prepare() function seems to be searching for an element with the id "seatsArray", which is not present. Although there are two elements with the name "seatsArray", the lack of an element with the designated id may prevent the array from being updated on the form.

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

Mastering the art of tab scrolling in VueJS using Bootstrap-vue

Currently, I am working on a VueJS project that utilizes bootstrap-vue. The issue I am facing is that when rendering a list of tabs, it exceeds the width of its parent container. To address this problem, I aim to implement a solution involving a set of but ...

Dynamic content displayed within adjacent div elements

I am currently working on a project where I am dynamically generating an outline by creating panels and labels in ASP.NET. Each node in the outline is defined by an outline number and outline text, which are obtained from a database that defines the relati ...

Converting database data into an array of objects using JavaScript

In my App.js file, I have the following code: const getPlayers = async()=>{ const players = await API.getPlayers(); setPlayers(players) } getPlayers() The following code is from my API.js file: const getPlayers = async() => { return getJson( ...

Using Laravel and AJAX to save multiple selected filters for future use

I've been struggling with this issue for a few weeks now and just can't seem to wrap my head around it. On my webpage, I've implemented four filters: a search filter, a year filter, a launch-site filter, and a country filter. Each of these ...

Ruby on Rails slider bar functionality

Currently, I am developing a video-focused application using Ruby 1.9.2 and Rails 3.1. One of the key features I need to implement is a slider bar that allows users to adjust the total duration of a video in real-time. Despite my attempts to use HTML5 fo ...

React app experiencing inconsistent loading of Google Translate script

In my React application, I have integrated the Google Translate script to enable translation functionality. However, I am facing an issue where the translator dropdown does not consistently appear on every page visit. While it sometimes loads properly, oth ...

Convert the JSON data received from a jQuery AJAX call into a visually appealing HTML table

Utilizing AJAX as the action, I have created a search form. In the success of the AJAX request, I am seeking a way to update a specific div without refreshing the entire page. Below is my form: <?php $properties = array('id' => &ap ...

extracting an attribute from a class's search functionality

Let's consider the following HTML structure: <div id="container"> <div> <div class="main" data-id="thisID"> </div> </div> </div> If I want to retrieve the value inside the data-id attribute ...

Can you explain the distinction between these two forms of functional components in ReactJs?

What sets apart these two code usages? In the FirstExample, focus is lost with every input change (It appears that each change triggers a rerender).. The SecondExample maintains focus and functions as intended. example import React, { useState } from &quo ...

What is the most effective method for invoking an inherited method (via 'props') in ReactJS?

From my understanding, there are two primary methods for calling an inherited method on ReactJS, but I am unsure which one to use or what the best practice is. class ParentCont extends React.Component { constructor(props) { super(props); t ...

The JSON node fails to return a value after inserting data through an ajax request

I'm encountering an issue with a jQuery plugin that loads JSON data through an AJAX call and inserts it into an existing object. When I attempt to reference the newly inserted nodes, they show up as 'undefined', despite the data appearing co ...

The ComponentDidUpdate function treats the previous state (prevState) and the current state (this

Initially, I had a state update function that looked like this: doChangeValue(data) { const dataNew = this.state.data dataNew[data.id] = data.value this.setState({ ...dataNew, [dataNew[data.id]]: data.value}) } However, I realized that thi ...

The teleport-controls feature is currently not functioning properly in VR mode with Aframe version 0.8.2

Having an issue with the teleport-controls under aframe 0.8.2. When in VR mode using Vive, only the curve appears after touching the trackpad of the controller, but the camera position does not change. However, in flat mode, both the curve and camera posit ...

PHP warning: Notice: Offset not defined

After creating an API to retrieve data from a database and display it as JSON in HTML, I encountered some PHP errors while trying to echo the data: Notice: Undefined offset: 80 in /opt/lampp/htdocs/ReadExchange/api.php on line 16 Notice: Undefined offse ...

Initiating an Ajax POST request when the onblur() event is triggered

Having an issue with Ajax. I'm trying to submit a changed value from an input field on the onblur() event, but there's a flicker that's bothering me. When I enter a new value and click away, the old value briefly flashes back before changi ...

Facing issues while attempting to retrieve the generated PDF through an Ajax-triggered controller action

I am having trouble downloading a PDF/XLSX file from the controller. I have tried using both jQuery and Ajax, but I can't seem to get it to work. Here is an example of the code in the controller: var filestream = new FileStream(pdfoutputpath + " ...

Applying CSS to an iframe using JavaScript: A Step-by-Step

I have an Iframe editor and I am trying to change some CSS inside the editor. However, when I attempt to apply the CSS, it does not affect the styles within the Iframe. <div id="editor" style="flex: 1 1 0%;"> <iframe src="https://editor.unlay ...

Ways to detect and display duplicate entries as a single entity

My object class is named Students and it contains attributes such as Student Name, Contact, and Twitter Handle. When fetching this data from Firebase, I am storing it in an array defined as var students: [Student] = []. Using Firestore, I execute a query a ...

Troubles encountered with example code: Nested class in an exported class - Integrating Auth0 with React and Node.js

I am currently attempting to execute tutorial code in order to create an authentication server within my React project. Below is the code snippet provided for me to run: // src/Auth/Auth.js const auth0 = require('auth0-js'); class Auth { co ...

Calculate how frequently an element showcases a particular style

I attempted to tally the occurrences of a specific class on an element, but I keep encountering the error message: $(...)[c].css is not a function Does jQuery have it out for me? Below is the code snippet in question: // hide headings of empty lists le ...