Vahn
Vahn

Reputation: 542

How to copy an input element with its value?

I have simple textboxes generated by AJAX.

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

What I'd like to do, when I press a button. The input is all copied inside a different div with its new value inserted by user.

I use

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

but, the value is not copied only the textbox

Upvotes: 1

Views: 3469

Answers (3)

Akar
Akar

Reputation: 5395

You can simply use:

$('#txt1').clone()

It will perform a deep clone of that element with all of its content.

NOTE: Cloning an element will also duplicate its ID if it has one. You should change any ids to classes beforehand.

This is from the documentation:

Note: Using .clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using class attributes as identifiers instead.

Upvotes: 0

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You need to make use of clone() so that you get the element with its value. Type anything in the textbox in the snippet below and press the Copy button.

//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>

If you want to add multiple cloned items then you will require to change the id of the input element and then append that to the page. You can do like this to achieve it,

//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>

Upvotes: 4

Dhruvin
Dhruvin

Reputation: 164

$(document).on('click','#myBtn',function(){
value=$('#txt1').val();

$('#myDiv').empty();
$('#myDiv').append($('#txt1').clone());
$('#txt1').val("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<input type='text' id='txt1' name='txt1_nm'  />
<button type="button" id="myBtn">Click Me</button>

<div id="myDiv"></div>

Upvotes: 0

Related Questions