开发者

jQuery text to input?

I have a simple layout with a textblock and one <a>, like:

tex开发者_JAVA百科t1 edit

When I click on the <a>, I want this textblock to become text input. How is that possible with jQuery?


Use jQuery replaceWith():

$(document).ready(function(){
    $("a").click(function(e){
        e.preventDefault();
        $(this).parent().replaceWith("<input />");
    });
});

http://jsfiddle.net/Dqkyg/1/


Furthermore, you can fill the textbox with the text outside the link like so:

$(document).ready(function(){
    $("a").click(function(e){
        e.preventDefault();
        var txt = $(".text").html();
        $(".text").replaceWith("<input value='" + txt + "' />");
    });
});

http://jsfiddle.net/Dqkyg/5/


The following will replace the edit with Save & Cancel options:

<div>
    <span class="text">testing</span> <a href='#'>test</a>
</div>

$(document).ready(function(){
    $("a").click(function(e){
        e.preventDefault();
        var txt = $(".text").html();
        $(".text").replaceWith("<input value='" + txt + "' />");
        $(this).replaceWith("<a href='#'>Save</a> | <a href='#'>Cancel</a>");
    });
});

http://jsfiddle.net/Dqkyg/6/


There are plenty of plugins that you can use... No need to reinvent the wheel

http://www.appelsiini.net/projects/jeditable


Hmm ... ur a bit unclear... but http://jsfiddle.net/mMYrf/4/

<div class="dataGrid">
    <span>test</span>
    <a href="#">edit</a>
</div>

And

$('.dataGrid a').click( function(e) {
        e.preventDefault();

        var EditGrid = $(this).parent().children('span');
        var DataTxt = EditGrid.text();
        var InputHtml = '<input type=text" value="'+DataTxt +'" />';

        $(this).text('Save?');
        EditGrid.html(InputHtml);
});


<div class="editable">This is the content.</div>
<script type="text/javascript">
    $(function() {
        $('.editable').each(function() {
            var a = $('<a href="#">edit</a>');
            (function(link, parent) {
                link.click(function() {
                    link.remove();
                    var textField = $('<textarea/>').val(parent.html());
                    parent.replaceWith(textField);
                    delete parent, link;
                });
            })(a, $(this));
            $(this).append(" ").append(a);
        });
    });
</script>

Working example: http://jsfiddle.net/BnH29/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜