MJJLAM MJJLAM - 2 months ago 6
HTML Question

Changing the html of a td tag dynamically

When the edit function is triggered the td with id "promo1" changes its html to show the options save delete rule and cancel. cancel is in an a tag with an onclick function called "cancel()". When clicked this should revert the td tag "promo1" back to the image set. However this doesnt work when the onclick is coming from the cancel a tag in the td tag "promo1" but it works when the cancel() function is triggered from the Cancel Button, any clues as to why this is occurring and fixes?



function edit(stringID){
console.log (stringID);
var id = '#promo' + stringID;
$("#promo1").html("<div style='width:200px'><a onclick='save()' style='margin-right:10px'><b>Save</b></a> <a onclick='save()' style='margin-right:10px'><b>Delete Rule</b></a> <a onclick='cancel()'><b>Cancel</b></a><div>");
}

function cancel() {
$("#promo1").html("<img src='dist/img/editButton.png'>");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
<tr style="border-bottom: 1px solid #f4f4f4;">
<td data-field="margin">15%</td>
<td data-field="promo">Promotion Role 1</td>
<td id="promo1" onclick="edit('1')" style="float:right"><img src="dist/img/editButton.png"></td>
</tr>
</table>

<button onclick="cancel()">Cancel Button</button>




Answer

I think this is what you are looking for:

function edit(stringID){
  console.log (stringID);
  var id = '#promo' + stringID;
  $("#promo1").html("<div style='width:200px'><a onclick='save()' style='margin-right:10px'><b>Save</b></a> <a onclick='save()' style='margin-right:10px'><b>Delete Rule</b></a> <a onclick='cancel()'><b>Cancel</b></a><div>");
}

function cancel() {
  $("#promo1").html("<img src='dist/img/editButton.png' onclick='edit(1)'>");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
   <tr style="border-bottom: 1px solid #f4f4f4;">
     <td data-field="margin">15%</td>
     <td data-field="promo">Promotion Role 1</td>
     <td id="promo1" style="float:right"><img src="dist/img/editButton.png" onclick="edit(1)"></td>
   </tr>
</table>

<button onclick="cancel()">Cancel Button</button>

Use onclick event on <img> instead of <td> and also include onclick='edit(1)' in your cancel(). Rest of your code works fine.