简体   繁体   中英

Changing input to div and vice versa

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.

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

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/

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]);
            }
        });
    });
});

A fiddle is here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM