MMM
MMM

Reputation: 77

Replacing html button with jquery

I've done some research regarding on how to replace/change the original html button to another. But neither the ways are working.

Here are my codes:

Javascript:

var editBtn = "editBtn" + id; //in order to get the id of the edit button
var cSave = document.getElementById(editBtn);
cSave.innerHTML = "<td><button id='saveBtn' onclick='saveChange(" + id + ");' >Save</button></td>";

The code above is just adding a button inside the existing button.

HTML:

<table>
<td>
<%
  out.println("<button id='editBtn" + mc.getId() + "' onclick='editMC(this.id);'>Edit</button>");
%>
</td>
</table>

The mc.getId() is a method to get the "id".

The latest approach that I've tried is mentioned below, but it's not working:

document.getElementById(editBtn).onclick = function() {saveChange(id)};

And:

$(document).ready(function () {
      $("#editBtn").replaceWith("<td><button id='saveBtn' onclick='saveChange(" + mcId + ");' >Save</button></td>");
});

Anyhow I can do to change the edit button to save button while onclick() is performed?

Upvotes: 1

Views: 94

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206101

Wrap the ID in quotes (unless it's a variable name):

document.getElementById("editBtn");

in jQuery it would be between this lines:

var mcId = 'bla';

function saveChange(){
  alert( mcId );
}


$(function () { // DOM ready shorthand


   $("#editBtn").click(function(){
      $(this).replaceWith("<button id='saveBtn'>Save</button>");
   });

  // Than, for your dynamically generated element use:

  $('#parent').on('click', "#saveBtn", function(){
     saveChange( mcId );
  });

});

jsBin demo

note that I used for static element reference a non-dynamic #parent. You should do the same (to prevent bonding to $(document) as it's quite expensive to listen to events all the way up the DOM).

jQuery .on() with event delegation for dynamically generated elements

Upvotes: 1

AnjumSKhan
AnjumSKhan

Reputation: 9827

You can change the text of the button from Edit to Save using innerHtml. You are actually putting some html inside the button element. Try

var cSave = document.getElementById(editBtn);
cSave.innerHTML = "Save";
cSave.onclick = function() {saveChange(id)};

Upvotes: 1

Related Questions