A function is unable to update a global variable

I have been working on a form that allows users to set the hour, with JavaScript validation in place to ensure there is input in the form. Initially, the global variable "userInputHours" is set to 0.

Within the function "validation()", when the user meets the criteria and fills in the form, the validation switches to the "else" statement and should update the global variable "userInputHours."

Finally, the HTML info-box should display the updated user input hours.

The Issue: I am struggling to make the user's form input value stay visible on the HTML info-box, as it quickly gets replaced by the original value of "userInputHours."

I've considered using AJAX, but it doesn't address the core problem at hand.

Working Scenarios:


Scenario-1: Enter digits in the "hours" field and click "submit-1":


Successes: The console log shows "You added: [the number you entered]."

Challenges: Checking the value of userInputHours from the console returns the initial value of [0], not the user-entered one. Although for a brief moment, less than a second, the user value briefly appears in the HTML form before reverting back to the original value.

Desired Outcome: The HTML info-box should reflect the number entered by the user.


Scenario-2: Clicking submit-2 triggers the "outsideValidation()" function, setting "userInputHours" to 5:


Accomplishments: The global variable "userInputHours" gets updated within the function. Confirming via console.log(userInputHours) confirms the update. The HTML info-box also updates accordingly.

Remaining Challenge: Since this test doesn't involve the "hours" field of the user form, entering a number in this field won't update the HTML info-box.

Expected Results: Functioning as intended; however, further adjustments are needed.

// Global variables.
var userInputHours = 0;

// Validation.
function validation() {

userInputHours = document.getElementById("userInputHours").value; // Works

  /* Validates blank fields */
  if (userInputHours == "") {
    console.log("A field is left blank"); // Works
    alert("Please fill in all fields!") // Works
    return false;
  }

    else {
      console.log("You added: " + userInputHours); // Works
      // User-entered value flashes momentarily before returning to global value
      document.getElementById("info-box-text").innerHTML = userInputHours; // Doesn't work.
      return true;
  }
}

/* Not part of validation. Triggered by button "submit-2" */
function outsideValidation() {
userInputHours = 5;
document.getElementById("info-box-text").innerHTML = userInputHours; // Works but not connected to user input in "hours" field.
}


/* Only executed upon saving script. */
document.getElementById("info-box-text").innerHTML = userInputHours; // Successful after saving script.
.box-1 {
  background-color: white;
  width: 100px;
  height: 100px;
}

#userInputHours {
  width: 100px;
}

#submit-1,
#submit-2 {
  height: 60px;
}
<form onsubmit = "return validation();">

 Hours:<br />
 <input id="userInputHours" type="text" name="hours" value=""><br /><br />

 <input id="submit-1" type="submit" value="Submit-1 (inside form)"><br /><br /> <!-- Submit button -->

</form>

<br />

<input id="submit-2" type="submit" value="Submit-2 (outside form)" onclick="outsideValidation()">

<br /><br />
<div id="info-box-title" class="info-box-title">Info-box - (you have set hours to):<br /></div>
<div id="info-box-text" class="info-box-text"></div>

Answer №1

When the validation function is called, the return value plays a crucial role in determining whether the form submission should proceed as usual.

If the return value of the function is true, then the default behavior will be triggered, and the browser will submit the form to the URL specified in the action attribute. If no URL is provided, the form will be submitted to the current page by default.

Upon form submission, you will navigate away from the current page, either loading a new one or refreshing the existing page based on the content of the action attribute. This action causes all JavaScript-stored values to be lost.

To prevent the data from being sent to the server, simply include return false in your code to halt the form submission process in both scenarios.

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

Why my attempts to alter numerous CSS elements using JQuery are failing?

Here's the code snippet I'm working with: var showThis = $(this).attr('id'); // div0, div1, div2 etc. $('#' + showThis).attr('style', 'background-color: #063 !important, height: 520px'); I am trying to mo ...

A JavaScript alert function that triggers no matter the return value

An alert is being sent by a function when a radio box's value returns as null, even though it should have a value that is not null. The issue lies in another function on the page that hides the tables where these radios are located, making it difficul ...

Add some flair to your list by animating the text within it

My goal is to add animation to the text within the list. Below is the code snippet: <div id="about" class="row section"> <div class="col-sm-8"> <h2 style="color:black;">About me!</h2> <ul> <li > ...

`To filter out JSON data that does not exist in Javascript, follow these steps:``

Utilizing JavaScript Fetch to retrieve JSON data, I am aiming to present the information in a well-arranged HTML layout. I encountered challenges when attempting to process certain content. The majority of the data objects I am parsing include images that ...

The Nestjs cronjob is having trouble accessing the injected service

After setting up a cronjob to call a service from another module, I encountered an issue where the console logged items were displaying correctly when running the method manually from the endpoint. However, once I added back the cronjob decorator, the serv ...

I'm not sure where to set the timeout for automatically refreshing the page

Trying to implement an auto-refresh feature on my page to fetch the most recent data from a database. I am anticipating that this will display the latest information without requiring any manual action, but unfortunately, new inputted data is not reflect ...

Firefox with Ajax bug bar

I have encountered an issue with my Navbar specifically on Firefox. The problem I am facing is that the Navbar is flickering, constantly growing and shrinking. Interestingly, this issue does not appear when using Chrome or Opera. I'm curious to know ...

When you press the submit button, the screen automatically scrolls down but no action is taken

I'm currently utilizing Selenium WebDriver (Java) with the Firefox driver. Upon trying to click the 'Submit' button on a particular page, it only results in scrolling down the screen slightly. The button itself does not register the click, c ...

When using QML, functions like Object.keys, Object.values, and JSON.stringify may return unexpected empty results

I have written a code that exposes a C++ object to QML, and I want to verify the declared properties of the object using native JS methods. However, they are not working as expected. I created a method called FizzBuzzDerived.properties, which functions cor ...

Tips for fixing the issue "Uncaught SyntaxError: Unexpected token S in JSON at position 0"

After referencing sols of SO, I am still unable to solve the error. I have a file dashboard.html which contains search conditions. When clicked, it calls loadtable.js. This loadtable.js file uses search.php to retrieve rows from a table. However, encount ...

Implementing user-driven filtering in a React table

When a user clicks on the submit button, data will be loaded. If no filter is applied, all data will be displayed. const submit = async (e: SyntheticEvent) => { e.preventDefault(); const param = { ...(certificateNo && ...

Exploring shader file content within three.js with the help of jQuery

I am trying to retrieve the content of a string that I have imported using HTML from within another script. To include the text file in question in the html file: <script src="shaders/fragmentshader.fs" id=fragmentshader></script> After impo ...

What is causing ui-route to fail in resolving state1 when transitioning from state2?

I have a program that consists of two views (lefthandmenu and content), with modules. When the user selects a module from a combo-list, $state.go() is called with the selected module name, and the views should update accordingly. See code samples below. I ...

Tips for organizing an object according to specific attributes

Within my table, I have implemented a feature that allows the display of only selected columns at a time. To achieve this, I store the chosen columns (table headings) in an array called selectedTableHeaders. The next step is to filter out a new array bas ...

Notification issues in Vue with Firebase Cloud Messaging while in foreground

I have been working on implementing FCM in my Vue PWA application. I have successfully configured background notifications, but I am facing issues with handling notifications when the app is open. Here is the code I am using. src/App.vue import firebase ...

Tips for creating a responsive tab indicator in Material UI?

I successfully integrated react router with material-ui and the routing system is working as expected. Clicking on a tab routes you to the corresponding component. However, I am facing an issue where the blue underline indicator that typically accompanies ...

Firmidable with Node.js

I am a beginner in the world of node.js and I have been soaking up knowledge from various resources like bootcamps and websites. My current challenge is with uploading a file using the formidable module within the node.js and express.js framework. Whenever ...

What is the best way to combine a collection of strings and HTML elements in a React application?

I am facing a challenge with my list of names. I typically use .join to add commas between each name, but one specific item in the list needs to display an icon of a star next to it based on a certain condition. The issue is that using join turns everyth ...

Extracting data on an AngularJS platform by using web scraping techniques

I have been working on an AngularJS application that currently retrieves JSON data from an API using http.get, and it's been working really well. Recently, I've been exploring the idea of passing a URL to a static webpage and scraping the result ...

Is it possible to test a Node CLI tool that is able to read from standard input with

I'm looking for a way to test and verify the different behaviors of stdin.isTTY in my Node CLI tool implementation. In my Node CLI tool, data can be passed either through the terminal or as command line arguments: cli.js #!/usr/bin/env node const ...