Tips for showing form data upon click without refreshing the webpage

Whenever I input data into the form and click on the calculate button, the result does not appear in the salary slip box at the bottom of the form.

However, if I refresh the page and then click on the calculate button, the results are displayed correctly in the box.

For more details, you can view the code by following this link: JsfiddleLink

"use strict";

const employeeName = document.querySelector("#input-name").value;
const grossPay = document.querySelector("#input-pay").value;
const bonus = document.querySelector("#input-bonus").value;
const allowance = document.querySelector("#input-allowance").value;
const incomeTax = document.querySelector("#input-tax").value;
const ei = document.querySelector("#input-ei").value;
const cpp = document.querySelector("#input-cpp").value;
const selectGender = document.querySelector(
  'input[name="gender"]:checked'
).value;
const selectDependent = document.querySelector(
  'input[name="dependent"]:checked'
).value;
const btnCalculate = document.querySelector("#submit");
const btnClear = document.querySelector(&q...

Answer №1

You're faced with the following declaration:

<button
      onclick="clearInput"
      id="submit"
      type="submit"
      class="btn btn-primary"
    >
      Calculate
    </button>

To address this, you need to create a function named "clearInput" to handle the button click event.

To resolve this issue, you can revise the above declaration like this:

<button
      id="submit"
      type="submit"
      class="btn btn-primary"
    >
      Calculate
    </button>

Then, include the following statements below:

let myForm=document.getElementById("my-form");
myForm.addEventListener("submit",(e)=>{
    //do your work here
    e.preventDefault(); 
})

Answer №2

Check out the changes I made to your code snippet here: https://jsfiddle.net/yz2fn4v6/1/

Here's what I updated:

  • Ensured all inputs now have a name attribute.
  • Established a reference to the <form /> element in JavaScript.
  • Adjusted the event listener on the submit button to target the form instead.
  • Utilized the FormData API for fetching data from the form.

While there are still some issues with the final fields, I believe you can troubleshoot them moving forward.

Answer №3

Ensure that the code snippet for retrieving values is moved within the event handler function.

btnCalculate.addEventListener("click", (e) => {
  e.preventDefault();
  const employeeName = document.querySelector("#input-name").value;
  const grossPay = document.querySelector("#input-pay").value;
  const bonus = document.querySelector("#input-bonus").value;
  const allowance = document.querySelector("#input-allowance").value;
  const incomeTax = document.querySelector("#input-tax").value;
  const ei = document.querySelector("#input-ei").value;
  const cpp = document.querySelector("#input-cpp").value;
  const selectGender = document.querySelector(
    'input[name="gender"]:checked'
  ).value;
  const selectDependent = document.querySelector(
    'input[name="dependent"]:checked'
  ).value;

  let totalAdditions = addition(bonus, allowance);

  let totalDeductions = Number(
    grossPay * deduction(ei, cpp) +
      grossPay *
        (incomeTaxDeduction(incomeTax) -
          genderDeduction(selectGender) -
          dependentDeduction(selectDependent))
  );
  totalDeductions.toFixed(2);

  nameSlip.innerText = employeeName;
  grossSalary.innerText = `$ ${grossPay}`;
  sumOfAdditions.innerText = `$ ${totalAdditions}`;
  sumOfDeductions.innerText = `$ ${totalDeductions.toFixed(2)}`;
  netSalary.innerText = `$ ${finalSalary(grossPay, totalAdditions, totalDeductions)}`;
});

The finalSalary function should be updated to accept totalAdditions and totalDeductions in its signature:

function finalSalary(grossPay, totalAdditions, totalDeductions)

To prevent form submission and page refresh, change the button type from submit to button:

<button
  onclick="clearInput"
  id="submit"
  type="button"
  class="btn btn-primary"
>
Calculate
</button>

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

Using Three.js to import and cast rays on a .obj model created in Blender

I have successfully imported a 3D terrain using Blender and the OBJLoader in Three.js. In addition, I have created a mesh (highlighted in yellow in the image below) that I want to follow the mouse cursor while it hovers over the terrain. I have attempted t ...

Stop the webpage from scrolling when clicking on a ui-grid field

Is there a way to prevent page scrolling when clicking on a row field in ui-grid? I'm working with a page that has ui-grid, and each row includes an anchor tag with a URL value linked and target="_blank" to open in a new tab like the example below: ...

How can one ensure that the column width in a Datatable adjusts dynamically based on the content within?

My data table creation code looks like this: var Master = $('#MasterGrid').DataTable( { "data": response, "columns":columns, "scrollX": true, }); $('#Mas ...

What is the process for changing the border color of a Select Component?

Is there a way to change the border color of a select component in Material UI library without directly setting the property in inspect elements? I can see it working when I set the property that way, but how can this be achieved using class override? htt ...

When attempting to log an AJAX/JSON request, the console.log statement is displaying 'undefined'

Being new to AJAX, I have encountered an issue that I believe others may have faced as well. Despite numerous attempts and extensive research, I am unable to find a solution to this error. I am confident that it is something simple. Any help would be gre ...

Creating a clickable table row in bootstrap with optimal effectiveness

Is it better to implement a clickable row using jquery or pure JS? Consider server and client efficiency Ensure compatibility with various browsers The jquery option: // my tr (row) class <tr class='clickable-row' data-href='url:www.g ...

Is it feasible to preserve the HTML form content data even after refreshing the page?

Can someone offer a suggestion that doesn't involve using Ajax? I'm wondering if there is a way to achieve this using JavaScript/jQuery or some other method. Here's my issue: When submitting a page, the action class redirects back to the sa ...

What could be causing the bottom of a vertical scroll bar to be cropped in Internet Explorer 11?

I am experiencing an unusual problem in IE11 where the content at the bottom of my page is being cut off along with the scroll bar that should allow for viewing that content. I have managed to resolve this issue in Chrome, Firefox, and Edge but I cannot se ...

Scrape data from LinkedIn search results using HtmlAgilityPack

Looking to fetch the top search result for a LinkedIn query. Check out this fiddle: https://dotnetfiddle.net/Vtwi7g Passing this link to 'html' variable: Targeting the first result : Wondering how to pass credentials for logging into Lin ...

The function replace does not exist in t(…)trim

I encountered an error in my code that breaks the functionality when checked using console.log. var map = L.map('map').setView([0, 0], 2); <?php $classesForCountries = []; if (have_posts()) : while (have_posts()) : the_post(); ...

Bootstrap modal not displaying in full view

I recently ran into some issues while using a jQuery plugin with my bootstrap modal on my website. After implementing jQuery.noConflict(), I encountered a problem where the program no longer recognized $, forcing me to replace all instances of it with jQue ...

Step-by-step guide on programmatically activating a radio button

I am working with a radio button and input field. I need the ability to programmatically toggle the radio button so that when this.iAreaOfCoverageForThresholdPasser.average-height is set to true, the radio button appears highlighted. Snippet of HTML: < ...

Utilizing Angular partials within specific views with the assistance of ui-router

I am currently working on developing a MEAN application and facing some challenges while handling ui-router. Within my index.html file, I have set up the template for the entire website including a header, sidebar, and content area where I have placed < ...

Steps to eliminate validation following the clearing of input fields

This is the code I've written for live validation using AJAX in an input field. My issue is that I want the validation to be removed if all inputs are deleted. <script type="text/javascript"> $(document).ready(function(){ ...

Looking to send information to a different website and get the response back using JavaScript?

Seeking assistance: I'm attempting to post my University seat number, 1da07cs102, to http://results.vtu.ac.in/results.php. This website uses rid as a name in form. How can I use JavaScript to retrieve my results from the specified site and display the ...

Deleting elements from the DOM in Vue.js

Utilizing Vue.js (version 3.x), I am dynamically rendering components. <div v-for="(i, index) in fields" > <my-component :id="index" ></my-component> <span class="delete-icon" @click="removeFi ...

"Step-by-step guide on placing an order for the button

I am currently working with material-ui and encountering a roadblock. My goal is to design a homepage for a dashboard where the various services are listed. I am attempting to organize these 6 buttons into 2 rows and 3 columns, totaling 6 buttons in all. A ...

How to Use JavaScript Function to Rotate an Entire Webpage

For my final project in a web design class, we were tasked with creating a website that showcases our skills. I've completed the assignment and now I want to add some interesting features to make it stand out. I'm interested in using -webkit-tra ...

Avoid having individual words centered on a single line of text

Currently, I'm in the process of developing a website using WooCommerce, WordPress, and Elementor. I've encountered an issue where only one word appears on each line and have tried various solutions such as hyphens, word-break, and line-break wit ...

Is it feasible to navigate through submenus using only the [Tab] key in CSS?

Is there a way to activate a submenu in a styled menu using only the [Tab] key so that the submenu becomes visible? I attempted to use the :focus pseudo-class ul li a:focus + ul li a ... and when t ...