field1x

JQuery change cell class and update data

I have a table on my page as shown below.

<table id="tbl"> <tr> <td class="field" id="field1s">field1x</td> <td class="field" id="field2s">field2x</td> <td class="field" id="field3s">field3x</td> <td class="field" id="field4s">field4x</td> <td class="xx">#</td> <td class="yy">#</td> </tr> </table> 

The texts of the fields in the line are changed to the entries in the <td class="xx"> field and are updated with the next click. It works great. But I want the xx class to change to aa and yy to bb when the user first presses <td class="xx">#</td> . Then the field can be changed to inputs, allowing the user to change the text. If the user clicks <td class="aa">#</td> again (previously <td class="xx">#</td> ), the text in the line can be updated, and if the user clicks <td class="bb">#</td> (formerly #), the line may return to its previous state. (Same as OK and CANCEL).

Here is a violin.

How can i do this? I prefer a simpler and faster solution.

+4
source share
2 answers

If you want to keep your classes, try this script .

I used .live() event delegation to keep consistent with changes to the class.

.toggle should be removed to prevent some errors. in thecodeparadox answer, if you press the edit button and then click the cancel button, the next click on the edit button will cause the wrong function.

Remember to replace .live() with .on() if you are using jQuery 1.7+ on your page.

0
source

Using jQuery .data() , you can easily solve this problem. I think you do not need to change the class.

  $('#tbl .xx').toggle( function() { $(this).siblings('.field').each(function(){ var t = $(this).text(); $(this).data('prev', t); $(this).html($('<input />',{'value' : t})); }); }, function() { $(this).siblings().each(function(){ var inp = $(this).find('input'); if (inp.length){ $(this).text(inp.val()); } }); } ); $('#tbl .yy').click(function() { $(this).siblings('.field').each(function(){ $(this).text($(this).data('prev')); }); }); 

Demo

+1
source

Source: https://habr.com/ru/post/1415793/


All Articles