简体   繁体   中英

How to trigger onclick dynamically with many elements on the page?

I have few values retrieved from DB. I need to update the product information using one on click function. Every click only the first product information is being populated. I want to load dynamically. Can I do it with onclick function? please help me.

    <tr>
<td id="product_name">Cheese</td>
<td id="product_id">12547777</td>
<td id="scheduled_time">04:00 PM</td>
<td id="distributor_name">Elle Nutrients</td>
<td id="order_status">Complete</td>
<td><i class="icon text-info fa fa-pencil" style="cursor: pointer;" onclick="addproduct(this.id)"></i></td>
</tr>
<tr>
<td id="product_name">Butter</td>
<td id="product_id">12577788</td>
<td id="scheduled_time">05:00 PM</td>
<td id="distributor_name">Oetker</td>
<td id="order_status">Waiting</td>
<td><i class="icon text-info fa fa-pencil" style="cursor: pointer;" onclick="addproduct(this.id)"></i></td>
</tr>

My script:

function addproduct(){

    var productname = this.$("#product_name").text();
    var productid = this.$("#product_id").text();
    var name = document.getElementById('new_productname');
    name.value = productname;
    var newid = document.getElementById('new_productid');
    newid.value = productid;
}

First, you're passing an argument to the function, but you don't have a parameter in the function definition.

Second, your syntax for DOM navigation is all wrong. Use methods like .closest() and .find() to navigate.

Third, IDs have to be unique. Use classes for repeated elements.

 function addproduct(element) { var row = $(element).closest("tr"); var productname = row.find(".product_name").text(); var productid = row.find(".product_id").text(); $("#new_productname").val(productname); $("#new_productid").val(productid); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td class="product_name">Cheese</td> <td class="product_id">12547777</td> <td class="scheduled_time">04:00 PM</td> <td class="distributor_name">Elle Nutrients</td> <td class="order_status">Complete</td> <td><i class="icon text-info fa fa-pencil" style="cursor: pointer;" onclick="addproduct(this)">X</i></td> </tr> <tr> <td class="product_name">Butter</td> <td class="product_id">12577788</td> <td class="scheduled_time">05:00 PM</td> <td class="distributor_name">Oetker</td> <td class="order_status">Waiting</td> <td><i class="icon text-info fa fa-pencil" style="cursor: pointer;" onclick="addproduct(this)">X</i></td> </tr> </table> New name: <input id="new_productname"> <br> New ID: <input id="new_productid">

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