Table of Contents
Problem analysis
Solution: Pass element reference
Things to note
Summarize
Home Web Front-end HTML Tutorial Troubleshooting and solving problems that cannot modify parameter values ​​in JavaScript functions

Troubleshooting and solving problems that cannot modify parameter values ​​in JavaScript functions

Oct 06, 2025 pm 07:27 PM

Troubleshooting and solving problems that cannot modify parameter values ​​in JavaScript functions

In JavaScript development, you often encounter situations where external variables need to be modified inside functions. However, if the value of the variable is passed to the function rather than a reference, directly modifying the function parameters cannot change the value of the original variable. This article will provide detailed analysis and solutions to this common problem.

Problem analysis

The core of the problem lies in the way parameters are passed in JavaScript. For basic types (such as numbers, strings, boolean values), the function parameters pass a copy of the value. This means that the parameters are modified inside the function, and in fact, the copy value is modified, not the value of the original variable.

In the provided code, the editFun function receives these parameters, expN, expD, expA, expT, and their values ​​are copied into local variables inside the function when called. Therefore, modifying the values ​​of these local variables inside the editFun function will not affect the values ​​of the original expName, expDate, expAmount, expType input fields.

Solution: Pass element reference

To solve this problem, you need to pass the reference to the input fields (i.e. the DOM element itself) to the editFun function, not their values. In this way, the value attribute of the DOM element can be modified directly by reference within the editFun function, thereby updating the value of the input field.

The modified code is as follows:

 const expAmount = document.getElementById("exp-amount");
const expName = document.getElementById("exp-name");
const expDate = document.getElementById("exp-date");
const expBtn = document.getElementById("exp-btn");
const expType = document.getElementById("exp-type");
const table = document.getElementById("table");
const tableChild = document.getElementById("table").childNodes;

expBtn.addEventListener("click", () => {
  const expN = expName; // Pass element reference const expD = expDate; // Pass element reference const expA = expAmount; // Pass element reference const expT = expType; // Pass element reference if (expT === "choose-type") {
    alert("Please choose the expense type!");
    return;
  }

  const tr = document.createElement("tr");

  // Serial No
  const td1 = document.createElement("td");
  const td1Text = document.createTextNode(tableChild.length - 1);
  td1.appendChild(td1Text);
  tr.appendChild(td1);

  // Expressnse Type
  const td2 = document.createElement("td");
  const td2Text = document.createTextNode(expT.value);
  td2.appendChild(td2Text);
  td2.classList.add("expT-data");
  tr.appendChild(td2);

  // Expense Name
  const td3 = document.createElement("td");
  const td3Text = document.createTextNode(expN.value);
  td3.appendChild(td3Text);
  td3.classList.add("expN-data");
  tr.appendChild(td3);

  // Expense Date
  const td4 = document.createElement("td");
  const td4Text = document.createTextNode(expD.value);
  td4.appendChild(td4Text);
  td4.classList.add("expD-data");
  tr.appendChild(td4);

  // Expense Amount
  const td5 = document.createElement("td");
  const td5Text = document.createTextNode(expA.value "Rs");
  td5.appendChild(td5Text);
  td5.classList.add("expA-data");
  tr.appendChild(td5);

  // Delete Btn
  const td6 = document.createElement("td");
  const td6Text = document.createTextNode("Delete");
  td6.append(td6Text);
  td6.classList.add("del-btn");
  tr.appendChild(td6);

  const td7 = document.createElement("td");
  const td7Text = document.createTextNode("Edit");
  td7.append(td7Text);
  td7.classList.add("edit-btn");
  tr.appendChild(td7);

  table.appendChild(tr);

  const editBtn = document.getElementsByClassName("edit-btn");
  editFun(editBtn, expN, expD, expA, expT);

  const delBtn = document.getElementsByClassName("del-btn");
  btnFun(delBtn);
});

// Function for Delete Button
function btnFun(delBtn) {
  Array.from(delBtn).forEach((e) => {
    e.addEventListener("click", (e) => {
      const a = e.currentTarget;
      a.parentElement.remove();
    });
  });
}

// Function for Edit Button
function editFun(editBtn, expN, expD, expA, expT) {
  Array.from(editBtn).forEach((e) => {
    e.addEventListener("click", (e) => {
      const siblings = e.currentTarget.parentElement.childNodes;

      expT.value = siblings[1].innerText;
      expN.value = siblings[2].innerText;
      expD.value = siblings[3].innerText;
      expA.value = siblings[4].innerText.split(" Rs")[0];
    });
  });
}

Key modifications:

  • In expBtn.addEventListener, modify const expN = expName.value; to const expN = expName;. Similarly, similar modifications are made to expD, expA, and expT. This is passed to the editFun function, the DOM element itself, not its value.
  • In the editFun function, use expT.value = siblings[1].innerText; to update the value of the input field. Similarly, similar modifications are made to expN, expD, and expA.

Things to note

  • Make sure that what is passed to the function is a reference to the DOM element, not their values.
  • Inside the function, use the .value attribute to access and modify the value of the input field.
  • Pay attention to data type conversion. The values ​​obtained from the DOM element are usually strings and may need to be typed according to actual situations. For example, if expAmount should be a number, you can convert it to a floating point number using parseFloat(siblings[4].innerText.split(" Rs")[0]).
  • siblings[4].innerText.split(" Rs")[0] in the code is used to remove the "Rs" character after the amount. In actual application, adjustments should be made according to actual conditions.

Summarize

By passing a reference to the DOM element, the value of the input field can be correctly modified inside the function. Understanding the way parameter passing in JavaScript is the key to solving this type of problem. When writing code, be sure to distinguish whether the passed value or reference, and choose the appropriate delivery method according to actual needs.

The above is the detailed content of Troubleshooting and solving problems that cannot modify parameter values ​​in JavaScript functions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

CSS tips: precisely hide specific text content without affecting parent elements CSS tips: precisely hide specific text content without affecting parent elements Sep 16, 2025 pm 10:54 PM

This tutorial details how to use CSS to accurately hide specific text content in HTML pages to avoid the problem of the entire parent element being hidden due to improper selectors. By adding exclusive CSS classes to the wrapping elements of the target text and using the display: none; attribute, developers can achieve refined control of page elements, ensuring that only the required parts are hidden, thereby optimizing page layout and user experience.

How to create a hyperlink to an email address in html? How to create a hyperlink to an email address in html? Sep 16, 2025 am 02:24 AM

Usemailto:inhreftocreateemaillinks.Startwithforbasiclinks,add?subject=and&body=forpre-filledcontent,andincludemultipleaddressesorcc=,bcc=foradvancedoptions.

How to make text wrap around an image in html? How to make text wrap around an image in html? Sep 21, 2025 am 04:02 AM

UseCSSfloatpropertytowraptextaroundanimage:floatleftfortextontheright,floatrightfortextontheleft,addmarginforspacing,andclearfloatstopreventlayoutissues.

How to add a tooltip on hover in html? How to add a tooltip on hover in html? Sep 18, 2025 am 01:16 AM

UsethetitleattributeforsimpletooltipsorCSSforcustom-styledones.1.Addtitle="text"toanyelementfordefaulttooltips.2.Forstyledtooltips,wraptheelementinacontainer,use.tooltipand.tooltiptextclasseswithCSSpositioning,pseudo-elements,andvisibilityc

How to set the lang attribute in HTML How to set the lang attribute in HTML Sep 21, 2025 am 02:34 AM

Setthelangattributeinthehtmltagtospecifypagelanguage,e.g.,forEnglish;2.UseISOcodeslike"es"forSpanishor"fr"forFrench;3.Includeregionalvariantswithcountrycodeslike"en-US"or"zh-CN";4.Applylangtospecificelementswhe

JavaScript external function call difficulty analysis: script location and naming specification JavaScript external function call difficulty analysis: script location and naming specification Sep 20, 2025 pm 10:09 PM

This article explores two common problems when calling external JavaScript functions in HTML: improper script loading time causes DOM elements to be unready, and function naming may conflict with browser built-in events or keywords. The article provides detailed solutions, including tweaking script reference locations and following good function naming specifications to ensure JavaScript code is executed correctly.

Capture mousedown events with parent element containing cross-domain iframes: Principles and limitations Capture mousedown events with parent element containing cross-domain iframes: Principles and limitations Sep 20, 2025 pm 11:00 PM

This article explores the challenge of capturing mousedown events on parent divs containing cross-domain iframes. The core problem is that browser security policies (same-origin policy) prevent direct DOM event listening on cross-domain iframe content. This type of event capture cannot be achieved unless the iframe source domain name is controlled and CORS is configured. The article will explain these security mechanisms in detail and their limitations on event interactions and provide possible alternatives.

What is the figure and figcaption element in html? What is the figure and figcaption element in html? Sep 13, 2025 am 03:44 AM

Thefigureelementgroupsself-containedmedialikeimagesorcharts,whilefigcaptionprovidesanoptionalcaption;togethertheyimproveaccessibilityandsemantics,asshowninalabeledsaleschartexample.

See all articles