Table of Contents
Variable declaration and scope
Event handling function
HTML Structure
Complete code example
Summarize
Home Web Front-end HTML Tutorial Dynamically modify the change of data through button click event

Dynamically modify the change of data through button click event

Aug 24, 2025 pm 09:18 PM

Dynamically modify the change of data through button click event

This article aims to solve the problem of dynamically modifying JavaScript variable data through HTML button click events. The article will explain in detail how to implement this functionality correctly, including avoiding common mistakes, using modern JavaScript syntax, and providing clear code examples. By reading this article, you will be able to master the skills to update variable data dynamically through button click events and apply it to your web development project.

In web development, it is often necessary to dynamically update the data on the page based on user interaction. Among them, it is a common requirement to modify the value of a variable through a button click event. This article will explain how to implement this function correctly and avoid some common mistakes.

Variable declaration and scope

First, we need to declare variables to store different datasets. It is recommended to use the const and let keywords instead of var. const is used to declare constants, i.e. variables whose values ​​are not modified, while let is used to declare variables that can be modified. This helps improve the readability and maintainability of the code.

 let chartdata = [];
const eqdata = [['a',2],['b',6],['r',9],['s',8]];
const debdata = [['p',2],['r',6],['r',9],['d',8]];
const hybdata = [['l',2],['k',6],['rr',9],['df',8]];

Event handling function

Next, we need to create an event handler function that will be executed when the button is clicked. In this function, we will update the chartdata variable based on the id of the button we clicked.

 function clicked(){
    const id = event.srcElement.id;
    if (id == 'eqty'){
        chartdata = eqdata;
    } else if (id == "debt"){
        chartdata = debdata;
    } else if (id == "hyb"){
        chartdata = hybdata;
    }
    // Here you can add code to update the chart, for example:
    // updateChart(chartdata);
    console.log(chartdata); // Output updated data};

Notice:

  • When comparing strings, be sure to use == or ==, instead of =. = is an assignment operator that assigns the value on the right to the variable on the left. Use == or === to correctly compare whether the values ​​of two strings are equal.
  • event.srcElement.id is used to get the id of the element that triggers the event.

HTML Structure

Finally, we need to create the HTML button and bind the onclick event to the clicked function.

 <div class="row" style="margin:auto; padding: 8px 8px 0" id="categories">
  <button id="eqty" class="btn btn-primary" style="'margin:" onclick="clicked()">Equity Chart</button>
  <button id="debt" class="btn btn-primary" style="'margin:" onclick="clicked()">Debt Chart</button>
  <button id="hyb" class="btn btn-primary" style="'margin:" onclick="clicked()">Hybrid Chart</button>
</div>

Complete code example

Combine the above code snippets to get a complete code example:

 <div class="row" style="margin:auto; padding: 8px 8px 0" id="categories">
    <button id="eqty" class="btn btn-primary" style="'margin:" onclick="clicked()">Equity Chart</button>
    <button id="debt" class="btn btn-primary" style="'margin:" onclick="clicked()">Debt Chart</button>
    <button id="hyb" class="btn btn-primary" style="'margin:" onclick="clicked()">Hybrid Chart</button>
</div>

<script>
    let chartdata = [];
    const eqdata = [[&#39;a&#39;,2],[&#39;b&#39;,6],[&#39;r&#39;,9],[&#39;s&#39;,8]];
    const debdata = [[&#39;p&#39;,2],[&#39;r&#39;,6],[&#39;r&#39;,9],[&#39;d&#39;,8]];
    const hybdata = [[&#39;l&#39;,2],[&#39;k&#39;,6],[&#39;rr&#39;,9],[&#39;df&#39;,8]];

    function clicked(){
        const id = event.srcElement.id
        if (id == &#39;eqty&#39;){
            chartdata = eqdata;
        } else if (id == "debt"){
            chartdata = debdata;
        } else if (id == "hyb"){
            chartdata = hybdata;
        }
        console.log(chartdata);
    };
</script>

Summarize

Through this article, we learned how to dynamically modify the data of JavaScript variables through button click events. Key points include:

  • Use const and let to declare variables.
  • Compare strings correctly.
  • Use event.srcElement.id to get the id of the element that triggered the event.
  • Update the value of the variable in the event handler.

By mastering these techniques, you can easily implement the ability to update variable data dynamically through button click events and apply it to your web development project.

The above is the detailed content of Dynamically modify the change of data through button click event. 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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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

PHP Tutorial
1587
276
Essential HTML Tags for Beginners Essential HTML Tags for Beginners Jul 27, 2025 am 03:45 AM

To get started with HTML quickly, you only need to master a few basic tags to build a web skeleton. 1. The page structure is essential, and, which is the root element, contains meta information, and is the content display area. 2. Use the title. The higher the level, the smaller the number. Use tags to segment the text to avoid skipping the level. 3. The link uses tags and matches the href attributes, and the image uses tags and contains src and alt attributes. 4. The list is divided into unordered lists and ordered lists. Each entry is represented and must be nested in the list. 5. Beginners don’t have to force memorize all tags. It is more efficient to write and check them while you are writing. Master the structure, text, links, pictures and lists to create basic web pages.

What is the name attribute in an input tag for? What is the name attribute in an input tag for? Jul 27, 2025 am 04:14 AM

Thenameattributeinaninputtagisusedtoidentifytheinputwhentheformissubmitted;itservesasthekeyinthekey-valuepairsenttotheserver,wheretheuser'sinputisthevalue.1.Whenaformissubmitted,thenameattributebecomesthekeyandtheinputvaluebecomesthevalueinthedatasen

Can you put a  tag inside another  tag? Can you put a tag inside another tag? Jul 27, 2025 am 04:15 AM

❌Youcannotnesttagsinsideanothertagbecauseit’sinvalidHTML;browsersautomaticallyclosethefirstbeforeopeningthenext,resultinginseparateparagraphs.✅Instead,useinlineelementslike,,orforstylingwithinaparagraph,orblockcontainerslikeortogroupmultipleparagraph

HTML `style` Tag: Inline vs. Internal CSS HTML `style` Tag: Inline vs. Internal CSS Jul 26, 2025 am 07:23 AM

The style placement method needs to be selected according to the scene. 1. Inline is suitable for temporary modification of single elements or dynamic JS control, such as the button color changes with operation; 2. Internal CSS is suitable for projects with few pages and simple structure, which is convenient for centralized management of styles, such as basic style settings of login pages; 3. Priority is given to reuse, maintenance and performance, and it is better to split external link CSS files for large projects.

How to embed a PDF document in HTML? How to embed a PDF document in HTML? Aug 01, 2025 am 06:52 AM

Using tags is the easiest and recommended method. The syntax is suitable for modern browsers to embed PDF directly; 2. Using tags can provide better control and backup content support, syntax is, and provides download links in tags as backup solutions when they are not supported; 3. It can be embedded through Google DocsViewer, but it is not recommended to use widely due to privacy and performance issues; 4. In order to improve the user experience, appropriate heights should be set, responsive sizes (such as height: 80vh) and PDF download links should be provided so that users can download and view them themselves.

How to create an unordered list in HTML? How to create an unordered list in HTML? Jul 30, 2025 am 04:50 AM

To create an HTML unordered list, you need to use a tag to define a list container. Each list item is wrapped with a tag, and the browser will automatically add bullets; 1. Create a list with a tag; 2. Each list item is defined with a tag; 3. The browser automatically generates default dot symbols; 4. Sublists can be implemented through nesting; 5. Use the list-style-type attribute of CSS to modify the symbol style, such as disc, circle, square, or none; use these tags correctly to generate a standard unordered list.

How to use the contenteditable attribute? How to use the contenteditable attribute? Jul 28, 2025 am 02:24 AM

ThecontenteditableattributemakesanyHTMLelementeditablebyaddingcontenteditable="true",allowinguserstodirectlymodifycontentinthebrowser.2.Itiscommonlyusedinrichtexteditors,note-takingapps,andin-placeeditinginterfaces,supportingelementslikediv

How to add an icon to your website title tab in HTML How to add an icon to your website title tab in HTML Aug 07, 2025 pm 11:30 PM

To add an icon to the website title bar, you need to link a favicon file in part of the HTML. The specific steps are as follows: 1. Prepare a 16x16 or 32x32 pixel icon file. It is recommended to use favicon.ico to name it and place it in the website root directory, or use modern formats such as PNG and SVG; 2. Add link tags to HTML, such as PNG or SVG formats, adjust the type attribute accordingly; 3. Optionally add high-resolution icons for mobile devices, such as AppleTouchIcon, and specify different sizes through the sizes attribute; 4. Follow best practices, place the icon in the root directory to ensure automatic detection, clear the browser cache after update, and check the correctness of the file path.

See all articles