简体   繁体   English

设置使用jquery选择的创建的输入文本

[英]set created input text selected using jquery

I have the following label: 我有以下标签:

<div id="email">
  <label>
    myemail@gmail.com
  </label>
  <i class="fa fa-edit"></i>
</div>

<div id="phone">
  <label>
    1234567890
  </label>
  <i class="fa fa-edit"></i>
</div>

When I click on the edit button I want to replace the label with an input and set the label value as selected. 当我单击编辑按钮时,我想用输入替换标签,并将标签值设置为选中状态。 Below is what i have tried so far: 以下是我到目前为止尝试过的方法:

$('.fa-edit').click(function(){
var info = $(this).closest('div');
var label = info.find('label');
var curr_value = label.text();
label.replaceWith('<input class="edit_input" type="text" value="'+curr_value+'" />')
  .focus(function(){
     //alert(this);
     this.select();
  });
// some code ..

the problem is that I can not set the input text as selected (ready to be replaced). 问题是我无法将输入文本设置为选中状态(准备替换)。 What should I do? 我该怎么办?

Create the input element and set the focus & select on it after you replace the label. 创建输入元素并设置焦点并在替换标签后对其进行选择。

Please check the below code: 请检查以下代码:

 $("#editBtn").click(function(){ var label = $(this).parent().find('label'); var curr_value = label.text().trim(); var newInput = $('<input class="edit_input" type="text" value="'+curr_value+'" />') label.replaceWith(newInput) newInput.focus().select() }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="email"> <label> myemail@gmail.com </label> <button id="editBtn">EDIT</button> </div> 

the value returned from .replaceWith is still the old <label /> reference, you need to re-select the input, so that you can focus it. 从.replaceWith返回的值仍然是旧的<label />引用,您需要重新选择输入,以便可以将其聚焦。

label.replaceWith('<input class="edit_input" type="text" value="'+curr_value+'" />')
$('.edit_input').off('focus').on('focus',function() {
    this.select()
}).trigger('focus')

use off() to remove previous event listener everytime the user click the edit button again. 每次用户再次单击编辑按钮时,请使用off()删除以前的事件侦听器。

i hope that help you. 希望对您有所帮助。

var label = $('label');
var curr_value = label.text();
label.replaceWith('<input class="edit_input" type="text" value="'+curr_value+'" />').focus(function(){
     $(this).select(); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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