User1899289003 User1899289003 - 2 months ago 6
Javascript Question

How to get value from a dynamic element

I need to get the value from a "p" element, I draw this "p" with jQuery and it's ok, then I have a button and when I click on it I want to display the value from "p" element but I don't get any information, here is a simple code example:



$(document).ready(function() {
$('#c').click(function() {
var p = $('#p1').val();
alert(p);
});

draw();
});


function draw() {
var html = "";
html += '<p id="p1">Hi</p>';

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

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<button id="c">Click</button>
<hr />
<div id="d">
</div>





How can I solve this? I don't get any console error.

Answer

Change :

var p = $('#p1').val();

To :

var p = $('#p1').text();