10

I'm trying to append an input text field and its value to be the value of a div.

Here is what I came up so far:

$(this).append('<input type="text" value=' $('#div1').val() '>');
jQuerybeast
  • 14,130
  • 38
  • 118
  • 196

4 Answers4

18

Don't use HTML strings for everything!

$(this).append(
    $('<input>', {
        type: 'text',
        val: $('#div1').text()
    })
);
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • Thank you. Probably the best way – jQuerybeast Jan 06 '12 at 20:16
  • @minitech have you got any resources on not using html strings? would love to read about it. Thanks – jQuerybeast Jan 06 '12 at 20:17
  • @jQuerybeast: Not off-hand. I could write a blog post about it now though :) The reason is you don't need to worry about escaping and such, or typing errors that only manifest themselves at runtime. – Ry- Jan 06 '12 at 20:26
  • 1
    @jQuerybeast http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly http://stackoverflow.com/questions/327047/what-is-the-most-efficient-way-to-create-html-elements-using-jquery – jbabey Jan 06 '12 at 21:00
  • @Ry- what are other parameters for this, how can i make a input field 'readonly'? – Khushboo Gupta Jul 29 '19 at 10:14
  • @KhushbooGupta: `readOnly: true`, but remember you can always chain stuff to it too, so `$('', …).prop('readOnly', true)`. – Ry- Jul 29 '19 at 10:16
  • @Ry- Thank you. Any document for this. I really wanna learn about this. – Khushboo Gupta Jul 29 '19 at 10:21
4
$(this).append('<input type="text" value='+ $('#div1').html()+ '>');
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
2
$(this).append('<input type="text" value=' + $('#div1').val() + '>');

don't forget to concatonate with +

Also, this assumes $(this) is an actual object.

Kai Qing
  • 18,793
  • 5
  • 39
  • 57
0

<div id="parent-dv">
    <lable for="posting">POST</lable>
    <textarea style="width:400px; height:auto;"></textarea>
    <input type="Submit" id="inputsubmit">
    <button id="clear">Clear</button>
</div>

$(document).ready(function(){
$('#inputsubmit').on('click',function(event)
 {
var $inpute2xt = $("#parent-dv").find('textarea').val();
$('#parent-dv').append("<p></p>").addClass("newp").append($inpute2xt);
   
 }
  );
 
 }
 );
 
 
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <style>
  </style>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
 
<div id="parent-dv">
 <lable for="posting">POST</lable>
 <textarea style="width:400px; height:auto;"></textarea>
 <input type="Submit" id="inputsubmit">
 <button id="clear">Clear</button>
 <p></p> 
 </div>
 

 
</body>
</html>