简体   繁体   English

如何使用jquery复制修改后的输入值

[英]How do you copy modified input values with jquery

I have a pretty complex form that I'm copying over to a print view by grabbing the entire .html() of the form. 我有一个非常复杂的表单,可以通过抓取表单的整个.html()复制到打印视图。 Overall it works great, but I'm running into a problem where it's getting the initially rendered values of input fields instead of the modified values. 总的来说,它很好用,但是我遇到了一个问题,它是获取输入字段的初始呈现值而不是修改后的值。

I've illustrated my problem here: http://jsfiddle.net/GAfrU/ 我已经在这里说明了我的问题: http : //jsfiddle.net/GAfrU/

Css 的CSS

#perform_copy {
width: 48px;
height: 24px;
background-color: #d7d7d7;
cursor: pointer;
padding: 0px 8px;
}

Html HTML

<div id="original">
    <input type="text" value="100"></input>
</div>
<div id="copy">
    </div>
<div id="perform_copy">Copy</div>

JS JS

function copy() {
   $("#copy").html($("#original").html());
}

$(document).ready(function() {
    $("#perform_copy").click(copy);
});

If you click copy it works properly with the unmodified value, but if you type a new value in it does. 如果单击“复制”,它将与未修改的值一起正常工作,但是如果您键入一个新值,它将起作用。 I realize typing the value in doesn't modify the HTML, and likewise editing the value with jQuery's .val() doesn't seem to fix the issue either. 我意识到输入值不会修改HTML,同样,使用jQuery的.val()编辑值似乎也无法解决问题。 Is a way I can copy the values from the input boxes into the actual DOM so they're be properly copied using jQuery's .html() function? 有一种方法可以将输入框中的值复制到实际的DOM中,以便可以使用jQuery的.html()函数正确复制它们?

$('#original').clone().appendTo('#copy');

Is a better way to copy HTML. 是复制HTML的更好方法。

http://api.jquery.com/clone/ http://api.jquery.com/clone/

use clone() .. to copy element 使用clone() ..复制元素

function copy() {
   $("#copy").html($("#original").clone());
}

$(document).ready(function() {
  $("#perform_copy").click(copy);
});

however.. since you are cloning the div with id as original.. you will end up having two elements with same ID which is invalid... so its better to change the id of cloned element so that IDs are unique 但是..由于您要克隆的ID与原始ID相同。.您最终将拥有两个具有相同ID的元素,这是无效的...所以最好更改克隆元素的ID,以便ID是唯一的

function copy() {
   $("#copy").html($("#original").clone().prop('id','copyoriginal'));
}

fiddle here 在这里摆弄

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

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