Reputation: 119
I've got some code to change input into div's
$(document).ready(function(){
$('#btnChange').click(function(){
$('#products, #mrp, #discount').replaceWith(function(){
return '<div id="'+this.id+'">'+this.value+"</div>";
});
});
});
What I want is to change them back on Second Click of the button from div to input with same id's and the same value. Or you could say undo what I did on first click.
Upvotes: 0
Views: 209
Reputation: 5764
You could store the existing elements and reload them like this:
$(document).ready(function () {
var collection = {};
$('#btnChange').click(function () {
$('#products, #mrp, #discount').each(function () {
if (this.nodeName.toLowerCase() === 'input') {
collection[this.id] = this;
$(this).replaceWith('<div id="' + this.id + '">' + this.value + "</div>");
} else {
$(this).replaceWith(collection[this.id]);
}
});
});
});
Upvotes: 0
Reputation: 1708
You can use jQuery's .toggleClass()
for this.
For example, if you have this form:
<form id="myForm">
<input type="text" id="myInput" class="visible clickable" />
<div id="myDiv" class="hidden clickable">Hello</div>
</form>
and .visible
and .hidden
definitions are:
.visible {
display: inline;
}
.hidden {
display:none;
}
then your javascript should be:
$('.clickable').click(function() {
$('#myForm .clickable').toggleClass('visible').toggleClass('hidden');
});
Here's a working jsFiddle: http://jsfiddle.net/A4Lvu/
Upvotes: 0
Reputation: 388326
Try
$(document).ready(function () {
$('#btnChange').click(function () {
$('#products, #mrp, #discount').replaceWith(function () {
if ($(this).is('input')) {
return $('<div />', {
id: this.id,
//use text to prevent html injection
text: this.value
});
} else {
return $('<input />', {
id: this.id,
value: this.innerHTML
});
}
});
});
});
Demo: Fiddle
Upvotes: 2