在hyperclick click上将标签更改为文本框 - mvc

时间:2016-05-23 08:40:35

标签: javascript jquery asp.net-mvc razor

当用户点击EDIT链接时,我想将标签更改为文本框。我正在做this post中讨论的相同事情,唯一的区别是我使用的是mvc razor语法DisplayFor而不是<label class="text-info">Saghir</label>。 我没有得到理想的结果,请告诉我哪里出错了。

HTML:

@Html.DisplayFor(m => m.FirstName, new { @id = "#attribute", @class = "text-info" })
<a href="#" id="edit">Edit</a>

JS:

<script>
$('#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();
    });
});
</script>

2 个答案:

答案 0 :(得分:2)

试试这个

HTML

$(document).ready(function (){
  $('#edit').click(function () {
     var text = $('.text-info').text();     
     var input = "<input id='attribute' type='text' class='text-fill' value='" + text + "' onfocusout='myFunction($(this))' />";
     $('.text-info').parent().text('').append(input);         
   });
});

function myFunction(e){
  var text = e.val(); 
  var dad = e.parent();  
  e.remove();
  dad.append("<label for='name' id='attribute' class='text-info'>" + text + "</label>");
}

JS

SQLite

例如小提琴 - http://jsbin.com/xegusicige/1/edit?html,js,output

答案 1 :(得分:2)

来自我的评论:

var textEl = document.getElementById("text");
document.getElementById("edit").addEventListener("click", function() {
  textEl.setAttribute("contenteditable", "true");
  textEl.focus();
}, false);
//per Dinesh J's suggestion:
textEl.addEventListener("blur", function() {
  this.setAttribute("contenteditable", "false");
}, false);
<button id="edit">
  Edit!
</button>
<div id="text">
  Random text
</div>

相关问题