Hello Readers,
Hope you are doing good today.
Today on My blog, I am going to explain how you can make labels in edit mode and update label text using JavaScript. First, you need to create label which you want to make editable and also create save and cancel button
<h2><div id="pName" class="text-info">Rafi Rizvi</div></h2><a href="#" id="edit">Edit</a>
<span id="spanButtons" style="display:none;">
<button id="btnUpdateName" class="btn btn-info" style=" border-radius: 1px;background: #87CEFA;border:1px solid #87CEFA;color:black">SAVE</button>
<button id="btnCancel" class="btn btn-info" style=" border-radius: 1px;background: #87CEFA;border:1px solid #87CEFA;color:black">CANCEL</button>
</span>
You need to include JavaScript library.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
In Below code we are updating text based on action.
<script type="text/javascript" language="javascript">
$(document).on('click', '#edit', function (e) {
e.preventDefault();
var pname = jQuery('#pName');
pname.replaceWith('<input type="text" id="txtName" value="' + pname.html() + '" style="margin-right:20xp"/>');
$(this).hide();
$('#spanButtons').show();
});
$(document).on('click', '#btnCancel', function (e) {
e.preventDefault();
$('#txtName').replaceWith('<p id="pName">' + jQuery('#txtName').val() + '</p>');
$('#spanButtons').hide();
$('#edit').show();
});
$(document).on('click', '#btnUpdateName', function (e) {
e.preventDefault();
functionUpdate();
});
$(document).on('focusout', '#txtName', function () {
functionUpdate();
});
$(document).on('keyup', '#txtName', function (e) {
if (e.which == 13) {
functionUpdate();
}
});
function functionUpdate() {
var name = jQuery('#txtName').val();
$('#txtName').replaceWith('<p id="pName">' + name + '</p>');
//jQuery('#edit1').addClass('fa fa-pencil').text('').attr('id', 'edit');
$('#spanButtons').hide();
$('#edit').show();
}
</script>
I hope this will help you. Please feel free to give us your feedback in comments.
0 Comment(s)