Eric Kim
Eric Kim

Reputation: 2698

jQuery get an entire input element, including its value

I have the following codes:

// Add a single component
$(document).on("click", ".copy-component .fa.fa-plus", function() {
    var component = $(this).closest(".one-component");
	var componentContainer = component.closest(".x_panel");

    componentContainer.append(component[0].outerHTML);
});
<div class="col-md-12 col-sm-12 col-xs-12 no-padding">
    <div class="x_panel border-true">
        <div class="x_title component-field">...</div>
        <div class="one-component">
            <ul class="nav navbar-right panel_toolbox panel-row">...
        </div>
        <div class="x_content eight no-margin-top component-container">
            <form id="demo-form" data-parsley-validate="" novalidate="">
                <div class="row">
                    <div class="col-lg-2 col-md-2 col-sm-4 col-xs-6">
                        <label class="input-upper-title">Cum. Len. (ft)</label>
                            <div class="has-checkbox">
                               <input type="checkbox"><input disabled="disabled" type="text" id="" class="form-control">
                            </div>
                    </div>
                    <div class="col-lg-2 col-md-2 col-sm-4 col-xs-6">...</div>
                    <div class="col-lg-2 col-md-2 col-sm-4 col-xs-6">...</div>
                    <div class="col-lg-2 col-md-2 col-sm-4 col-xs-6">...</div>
                </div>
            </form>
        </div>
    </div>
</div>

And this is how it currently looks like: enter image description here As you can see, the input values were not copied.

The first row was originally there, but the second row was dynamically added by clicking "Add" button at the bottom.

When I click the icon "+" (.fa.fa-plus), I want a new component to be appended, including what's inside the input field right now.

Here's what I want: enter image description here

How can I modify my jQuery code to achieve this?

Upvotes: 1

Views: 59

Answers (1)

Satpal
Satpal

Reputation: 133403

You should append .clone() element instead of getting outerHTML and appending it.

Create a deep copy of the set of matched elements.

componentContainer.append(component.clone(true));

$('button').click(function() {
  $('#a').clone().appendTo('div');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add</button>
<input id="a" />
<div>

</div>

Upvotes: 1

Related Questions