简体   繁体   中英

Edit HTML Table Data cell using Jquery

I have an HTML table, and each cell of the table will have two data attributes. What I'm trying to do is set a button to switch the value being shown in the table between those two attributes.

<table class="table1">
<tbody>
<tr>
<td data-original="A" data-new="B"> A </td>
</tr>
</tbody>
</table>

I'm able to set new text and get attributes outside the table, but whenever I try to within the table I keep receiving an error:

'Uncaught -> TypeError: undefined is not a function'.

I've been receiving this error for a number of commands $('td').text() , .val() , .attr('td') , .getAttribute() . Am I missing a plugin or something for getting and setting values from tables?

ANSWER: I figured out the reason, I was an idiot and didn't mention that there would be numerous TD elements with repeating tags. I eventually used Underscore.js's each method to iterate through them and parts of the below answer to swap the values.

Just made a Fiddle :

$("button").on("click", function () {
    $("td").text($.trim($("td").text()) == $("td").data("original") 
      ? $("td").data("new") : $("td").data("original"));
});

to switch between the data-original and data-new values by checking the current text in the td and using a ternary operator. By using trim() for the initial text issues in case of whitespace are taken care of (as I just noticed that you have whitespace in your example td).

Just in case the button isn't already in the DOM when the page is initially loaded, you have to adjust the on() to delegate the click event from a static parent element to the button, eg like this: $(document).on("click", "button", function () { ...
Instead of $(document) every other static parent element can be used.

And as you mentioned that the table will have multiple tds with data-attributes, I've just adjusted the Fiddle to take care of that:

$("button").on("click", function () {
   $("td").each(function () {
    $(this).text($.trim($(this).text()) == $(this).data("original") ?   
             $(this).data("new") : $(this).data("original"));
   });
});

I don't know how .text() didn't work for you.

To set text inside td elements, you use .text() . To get the data inside data-current or data-new , jQuery has a handy function .data(tag) , for example $(sel).data('current') .

Here's a fiddle displaying usage of this on your problem.

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