jQuery 单击编辑超链接时将标签更改为文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16792502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:47:47  来源:igfitidea点击:

Change Label to Textbox on edit hyperlink click

jqueryruby-on-railstwitter-bootstrap

提问by Saghir A. Khatri

I am new to ruby on rails and twitter bootstrap. Accept my apologize if my question sound dumb. I am using twitter bootstrap for my site design. I have been trying to use bootstrap to change my label to textbox using hyperlink button click.

我是 ruby​​ on rails 和 twitter bootstrap 的新手。如果我的问题听起来很愚蠢,请接受我的道歉。我正在使用 twitter bootstrap 进行我的网站设计。我一直在尝试使用引导程序通过单击超链接按钮将我的标签更改为文本框。

<div class="control-group">
    <label for="name" class="control-label"><p class="text-info">Saghir<i class="icon-star"></i></p></label>
    <div class="controls">
        <a href="#">Edit</a>
    </div>

but I am unable to do so, should I use jquery to do so, or I can use bootstrap for that. Please point me to right direction. Thanks in advance

但我无法这样做,我应该使用 jquery 这样做,或者我可以使用引导程序。请指出我正确的方向。提前致谢

EditCode is updated with hyperlink(it could be button too). it is like, when I click on "Edit" hyperlink my label should show content "Saghir" that can be used using placeholder attribute of bootstrap. I can submit form to update values to database.

编辑代码用超链接更新(也可以是按钮)。就像,当我点击“编辑”超链接时,我的标签应该显示可以使用引导程序的占位符属性使用的内容“Saghir”。我可以提交表单以将值更新到数据库。

回答by rails_id

I think you need jQuery for it. Try this :

我认为你需要jQuery。尝试这个 :

$('#edit').click(function() {
 var text = $('.text-info').text();
 var input = $('<input id="attribute" type="text" value="' + text + '" />')
 $('.text-info').text('').append(input);
 input.select();

 input.blur(function() {
   var text = $('#attribute').val();
   $('#attribute').parent().text(text);
   $('#attribute').remove();
 });
});
.control-label .text-info { display:inline-block; }
 
<label for="name" class="control-label"><p class="text-info">Saghir</p><i class="icon-star"></i></label>
<div class="controls">
   <a href="#" id="edit" class="btn">Edit</a>
</div>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>

Update

更新

If you want change label to input and text of label put into placeholder of input, try this for

如果要将标签更改为输入并将标签文本放入输入的占位符,请尝试此操作

$('#edit').click(function() {
 var text = $('.text-info').text();
 var input = $('<input type="text" placeholder="' + text + '" />')
 $('.text-info').text('').append(input);
});
.control-label .text-info { display:inline-block; }
<label for="name" class="control-label"><p class="text-info">Saghir</p><i class="icon-star"></i></label>
<div class="controls">
   <a href="#" id="edit" class="btn">Edit</a>
</div>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>

jsfiddlejsfiddle 2

jsfiddlejsfiddle 2

回答by Amyth

As Chris said, Bootstrapdoes not provide this functionality as it is a front-end framework. you can use jQueryto achieve this. Though, you'll need to add some custom id's or classes to your elements to make sure you are only selecting the required elements. You can do something like the following:

正如 Chris 所说,Bootstrap不提供此功能,因为它是一个前端框架。你可以用它jQuery来实现这一点。但是,您需要向元素添加一些自定义 id 或类,以确保您只选择所需的元素。您可以执行以下操作:

HTML

HTML

<div class="control-group">
    <label for="name" class="control-label">
        <p class="text-info">Saghir<i class="icon-star"></i></p>
    </label>
    <input type="text" class="edit-input" />
    <div class="controls">
        <a class="edit" href="#">Edit</a>
    </div>
</div>

jQuery

jQuery

$(document).ready(function() {
    $('a.edit').click(function () {
        var dad = $(this).parent().parent();
        dad.find('label').hide();
        dad.find('input[type="text"]').show().focus();
    });

    $('input[type=text]').focusout(function() {
        var dad = $(this).parent();
        $(this).hide();
        dad.find('label').show();
    });
});

CSS

CSS

.edit-input {
    display:none;
}

Here is a working JSFiddlefor your reference.

这是一个有效的JSFiddle供您参考。

回答by davidkonrad

Use a hidden input

使用隐藏输入

<div class="control-group">
    <label for="name" class="control-label"><p class="text-info">Saghir<i class="icon-star"></i></p></label>
    <input type="text" class="input-medium" style="display:none;">
    <div class="controls">
        <a href="#" onclick="edit(this);">Edit</a>
    </div>
</div>

When user click on "Edit", grab the text from text-info(eg Saghir), hide the label, show the input and set the inputs placeholder-attribute.

当用户单击“编辑”时,从text-info(例如 Saghir)获取文本,隐藏标签,显示输入并设置输入占位符属性。

function edit(element) {
    var parent=$(element).parent().parent();
    var placeholder=$(parent).find('.text-info').text();
    //hide label
    $(parent).find('label').hide();
    //show input, set placeholder
    var input=$(parent).find('input[type="text"]');
    $(input).show();
    $(input).attr('placeholder', placeholder);
}

working fiddle : http://jsfiddle.net/TKW74/

工作小提琴:http: //jsfiddle.net/TKW74/

回答by VIP

I know its a old question, But just added Update option to Saghirs answer ,

我知道这是一个老问题,但只是在 Saghirs 答案中添加了更新选项,

http://jsfiddle.net/integerz/k3p4vhnb/

http://jsfiddle.net/integerz/k3p4vhnb/

    function edit(element) {
        var parent = $(element).parent().parent();
        var placeholder = $(parent).find('.text-info').text();
        //hide label
        $(parent).find('label').hide();
       //show input, set placeholder
        var input = $(parent).find('input[type="text"]');
        var edit = $(parent).find('.controls-edit');
        var update = $(parent).find('.controls-update');
        $(input).show();
        $(edit).hide();
        $(update).show();
        //$(input).attr('placeholder', placeholder);
    }

    function update(element) {
        var parent = $(element).parent().parent();
        var placeholder = $(parent).find('.text-info').text();
        //hide label
        $(parent).find('label').show();
        //show input, set placeholder
        var input = $(parent).find('input[type="text"]');
        var edit = $(parent).find('.controls-edit');
        var update = $(parent).find('.controls-update');
        $(input).hide();
        $(edit).show();
        $(update).hide();
    //$(input).attr('placeholder', placeholder);
    $(parent).find('label').text($(input).val());
}

This will enable the user to get back to the normal mode. Also the Ajax call for update can be triggered on update function.

这将使用户能够回到正常模式。也可以在更新函数上触发 Ajax 调用更新。

回答by Felix B?hme

I fiddled a litte more with Amyth's answer. This one just lets you click the text to edit it. You just need to add a class to any text element to enable the functionality. Enter key updates the text. Click outside the input to abort.

我对 Amyth 的回答稍加改动。这只是让您单击文本进行编辑。您只需要向任何文本元素添加一个类即可启用该功能。Enter 键更新文本。单击输入外部以中止。

HTML:

HTML:

<span class="edit-on-click">Click to edit</span>

JS:

JS:

$(document).ready(function() {
  $('.edit-on-click').click(function() {
    var $text = $(this),
      $input = $('<input type="text" />')

    $text.hide()
      .after($input);

    $input.val($text.html()).show().focus()
      .keypress(function(e) {
        var key = e.which
        if (key == 13) // enter key
        {
          $input.hide();
          $text.html($input.val())
            .show();
          return false;
        }
      })
      .focusout(function() {
        $input.hide();
        $text.show();
      })
  });
});

JSFiddle

JSFiddle

Update (implementing AJAX to update db value):

更新(实现 AJAX 来更新数据库值):

Here's how I ended up using it in practice: this uses data attributes on the original element for id, model, and field to update in an ajax request. (This is from a Django app using Bootstrap, so some lines might be obsolete for you depending on your setup.)

这是我最终在实践中使用它的方式:这使用原始元素上的数据属性,用于 id、模型和字段以在 ajax 请求中更新。(这是来自使用 Bootstrap 的 Django 应用程序,因此根据您的设置,某些行可能已过时。)

HTML:

HTML:

<span onclick="editOnClick(this)" 
      data-id="123" 
      data-model="myapp.MyModel" 
      data-field="my_field">Click to edit</span>

JS:

JS:

function editOnClick(el) {
    var $text = $(el),
            $input = $('<input type="text" />');

    $text.hide()
            .after($input);

    $input.val($.trim($text.html())).show()
            .tooltip({title:"press ENTER to save<br>click outside to cancel", container:"body", trigger:'focus', html:true})
            .focus()
            .keypress(function(e) {
                var key = e.which;
                if (key == 13) // enter key
                {
                    $.ajax({
                        type: "POST",
                        data: {
                            value:$input.val(),
                            obj_id:$text.attr('data-id'),
                            obj_model:$text.attr('data-model'),
                            obj_field:$text.attr('data-field'),
                            csrfmiddlewaretoken:'{{ csrf_token }}'
                        },
                        url: "{% url 'edit_on_click' %}",
                        cache: false,
                        dataType: "html",
                        success: function(html, textStatus) {
                            $input.hide();
                            $text.html(html)
                                    .show();
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert('Error: ' + XMLHttpRequest.responseText)
                        }
                    });

                    return false;
                }
            })
            .focusout(function() {
                $input.hide();
                $text.show();
            })
}