javascript - 如何复制输入元素及其值?

标签 javascript jquery html

我有 AJAX 生成的简单文本框。

<input type='text' id='txt1' name='txt1_nm'  />

当我按下一个按钮时,我想做什么。输入全部复制到不同的 div 中,并由用户插入新值。

我用

$('#txt1').html();

但是,值不会只复制到文本框

最佳答案

您需要使用clone() 来获取元素及其值。在下面代码段的文本框中输入任何内容,然后按 Copy 按钮。

//detect the click of the copy button
$('#copyBtn').click(function(){
  //get the clonned element
  var inputElement = $('#txt1').clone();
  //add clonned element to a new div
  $('#copiedDiv').html(inputElement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type='text' id='txt1' name='txt1_nm'  />
</div>
<div id='copiedDiv'></div>
<button id='copyBtn'>Copy</button>

如果您想添加多个克隆项,则需要更改 input 元素的 id,然后将其附加到页面。你可以这样做来实现它,

//detect the click of the copy button
$('#copyBtn').click(function(){
  //get the last input item
  var $inputEl = $('input[name="txt1_nm"]:last');
  //get the next id number
  var num = parseInt( $inputEl.prop("id").match(/\d+/g), 10 ) +1;
  //clone and set a new id for this element
  var $cloneEl = $inputEl.clone().prop('id', 'txt'+num );
  //add clonned element to a new div
  $('#copiedDiv').append($cloneEl);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type='text' id='txt1' name='txt1_nm'  />
</div>
<div id='copiedDiv'></div>
<button id='copyBtn'>Copy</button>

关于javascript - 如何复制输入元素及其值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48762251/

相关文章:

javascript - JTEXTPANE 多彩前景设置

javascript - 如何使用缩略图和箭头创建图片库

javascript - 隐藏没有 val 的 div (ASP.NET MVC)

javascript - AJAX 回调从未调用,不成功或错误

javascript - JSON.parse() 永远不会完成

javascript - 使用 $.each() 获取数据属性

javascript - 使用JavaScript创建三个Js标签方法

javascript - 如何让 JavaScript 定位到 iframe?

javascript - 使用 Ajax 验证表单时未定义

html - 将右侧 float 的 div 扩展到左侧