Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to clone form field values in jQuery or javascript?

jQuery has a clone() function that clones the actual form with no problem, but it doesn't preserve any values that have been entered into the form.

Is there a way to get around this?

Sample code would be much appreciated.

like image 322
Fred Avatar asked Jul 14 '10 21:07

Fred


People also ask

What is cloning in jQuery?

jQuery clone() Method The clone() method makes a copy of selected elements, including child nodes, text and attributes.

How do you clone an object in jQuery?

To clone an element using jQuery, use the jQuery. clone() method. The clone() method clones matched DOM Elements and select the clones. This is useful for moving copies of the elements to another location in the DOM.


2 Answers

Stemming from the notes, here's a solution. With the following form:

<form id="old">     <textarea>Some Value</textarea>     <input type="text" value="Some Value" />     <input type="checkbox" value="bob" checked />     <br /> </form>  <input type="button" value="Clone" id="clone" /> 

This jQuery works, including the textareas:

$( 'input#clone' ).click(     function()     {       $( 'form#old textarea' ).text( $( 'form#old textarea' ).val() )       $("form#old").clone().attr( 'id', 'new_form' ).appendTo("body")      } ) 

​Demo: http://jsfiddle.net/Jux3e/

like image 33
hookedonwinter Avatar answered Sep 27 '22 22:09

hookedonwinter


ran into the same problem, simple solution:

// touch all input values $('input:text').each(function() {     $(this).attr('value', $(this).val()); });  var clones = $('input:text').clone(); 

the trick is that this will change the actual 'value' attribute in the DOM tree, otherwise the data you enter 'on-the-fly' only exists in the DOM 'state'

like image 177
sled Avatar answered Sep 27 '22 22:09

sled