简体   繁体   中英

Dynamically adding Content to a table Cell

Hi My table is as follows, what i want to do is get the current value from the cell and increase by one and then print it back in the same cell, Everything is illustrated below.

<table>
        <thead>
            <tr>
                <th width="5%">No</th>
                <th width="10%">Model No</th>
                <th width="15%">Model/Make</th>
                <th width="20%">Price</th>
                <th width="20%">Available Quantity</th>
                <th width="20%">Add to or Remove from Cart</th>
                <th width="10%">No of Items</th>
            </tr>
        </thead>
        <tbody>

            <tr>
                <td>1</td>
                <td>001</td>
                <td>SONY</td>
                <td>5000</td>
                <td>10 Units</td>               
                <td align="center">
                <input type="image" src="images/add.png" name="add" id="add" onclick="add();"/>
                </td>
                <td id="The_Dynamic_Cell">0</td>

            </tr>

        </tbody>
    </table>

The Java Script

function add(){

Get the current Content of the cell (id="The_Dynamic_Cell") and increase the value by 1 (content++) and re populate the cell with new value. 

}

How can I achieve the above? Thanks in advance

Suggestion, don't bind events within the DOM element. Here's a simple way to bind a click event. Notice that the jsfiddle option No Wrap - in body - Basically this means that you have a script tag at the end (inside) your body tag to make sure the elements have rendered in the DOM by the time you run this code:

var addButton = document.querySelector("#add");
var cell = document.querySelector("#The_Dynamic_Cell");

addButton.onclick = function add(e){
    cell.innerText =  parseInt(cell.innerText, 10) + 1; 
}

Example

If you must adapt this to work with your above example (binding on the element), then you can try the following:

var cell = document.querySelector("#The_Dynamic_Cell");

function add(e){
    cell.innerText =  parseInt(cell.innerText, 10) + 1; 
}

Example

You can read more events here or on MDN

   function add() {
     var tdEle = document.getElementById("The_Dynamic_Cell");
     tdEle.innerText = parseInt(tdEle.innerText, 10) +1;
   }

This will get the cell with ID The_Dynamic_Cell and will increment its value by 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM