0

I have a form on a page. The form contains text inputs, checkboxes, selects (interactive elements). I want the user to be able to click a button, and reproduce a portion of the form elsewhere on the page, in the current state, preserving the text entered, the checkboxes checked, and the selects selected.

Currently I have this, which appends the HTML, however it grabs the HTML in the state it was when the page was loaded.

$('#create_unique_field').click( function() {
    $('#unique_field_cnt').append($('#template_cnt').html());
});

I have tried using delegation using on(), like so, with the same results.

$( 'body' ).on( 'click', '#create_unique_field', function() {
    $('#unique_field_cnt').append($('#template_cnt').html());
});

What I want is the current state of the HTML, not the HTML at the point when the page was loaded. How can I accomplish this?

Goose
  • 4,764
  • 5
  • 45
  • 84

1 Answers1

2

It doesn't work that way, you need to bind values of form elements and create new form elements with that data. More or less it falls on var inputText = $('#someInputEl').val(); and then applying that values on new form elements and THEN inserting it.

Try this:

<input type="text" id='one'>
<button>submit</button>   
<div id="target"></div>   

$(function(){
    $('button').click(function(){
        var inputVal = $('#one').val();
        var newInputEl = $("<input type='text' id='two'>");
        newInputEl.val(inputVal);
        $('#target').html( newInputEl );
    });    
});

This is rough sketch but you should make it work this way, here is fiddle.

Drops
  • 2,680
  • 18
  • 16
  • I'll accept the answer, as it is a good one, but I still would imagine that since the html exists in my inspect element, free for me to copy, that javascript/jquery must have a way to access the current state of HTML as well. – Goose May 20 '15 at 20:35
  • 1
    Take a look at [this answer](http://stackoverflow.com/questions/16483560/how-to-implement-dom-data-binding-in-javascript). You mentioned button click so I expected that you didn't want two-way binding. – Drops May 20 '15 at 20:38