Skip to content Skip to sidebar Skip to footer

Button In A List, How To Make It ''edit'' The Good Line?

I'm trying to make list rows editable with a click button. The 'edit' button should edit the line it matches with. Right now, the edit button only edit the first row. It's for a li

Solution 1:

Instead of all this, just have a click of the button make the current row contentEditible = "true". No dynamically created HTML needed.

// Get all the "buttons" into an Array
let buttons = [].slice.call(document.querySelectorAll(".edit > span"));

// Loop over the array
buttons.forEach(function(button){
  // Set up event handler
  button.addEventListener("click", function(){
    // Locate the editable cell in the current row and make that cell editible
    this.closest("tr").querySelector(".editible").contentEditable  = "true";
  });
});

// For resetting the cells after editing.....

// Get all the editible cells into an Array
let editibleCells = [].slice.call(document.querySelectorAll(".editible"));

// Loop over the array
editibleCells.forEach(function(cell){
  // Set up event handler
  cell.addEventListener("blur", function(){
    this.contentEditable  = "false";  // Turn off editable for the current cell
  });
});
body { font-family:Calibri, Arial, Helvetica; }
table, td { border:1px dashed #e9e9e9; padding:3px; }
.edit > span { display:inline-block; border:1px solid #e0e0e0; padding:5px; background-color:#d0d0d0; cursor:pointer; border-radius:3px; }
[contenteditable="true"] { background:yellow; }
<table>
  <tr>
    <td>Row 1, Cell 1</td>
    <td class="editible">Row 1, Cell 2</td>
    <td>Row 1, Cell 3</td>
    <td class="edit"><span>Edit</span></td>
  </tr>
  <tr>
    <td class="editible">Row 2, Cell 1</td>
    <td>Row 2, Cell 2</td>
    <td>Row 2, Cell 3</td>
    <td class="edit"><span>Edit</span></td>
  </tr>
  <tr>
    <td>Row 3, Cell 1</td>
    <td>Row 3, Cell 2</td>
    <td class="editible">Row 3, Cell 3</td>
    <td class="edit"><span>Edit</span></td>
  </tr>
</table>

Solution 2:

So, since Angular isn't specified, I'm gonna give a general JavaScript solution.

First, let's add a class to every button to make sure this is bound to the correct button from javascript side of things.

Also make sure to add .editable class to every td

<button class="click-trigger">Edit</button>

 <td  class="editable">{{offer.namePostfix}}</td>
   <td id="offerUrl" class="editable">{{offer.url}}</td>

Second, add the following js code:

let buttons = document.querySelectorAll('.click-trigger');

// Let's setup the event listeners
buttons.forEach(btn => btn.addEventListener('click', editOfferInfos);

function editOfferInfos() {
   let clickedButton = this;
   /* then you can just use .querySelectorAll to swap the elements with editable items */
  clickedButton.parentNode.querySelectorAll('.editable').forEach( item => {
     item.innerHTML = "<input type='text'>"
  });
}

Post a Comment for "Button In A List, How To Make It ''edit'' The Good Line?"