I want to add text to an existing div, when I click the Button with the id #add. But this is not working.
Here my code:
$(function () {_x000D_
$('#Add').click(function () {_x000D_
$('<p>Text</p>').appendTo('#Content');_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="Content">_x000D_
<button id="Add">Add</button>_x000D_
</div>
_x000D_
I hope you can help me.
Your html is invalid button
is not a null tag. Try
<div id="Content">
<button id="Add">Add</button>
</div>
Very easy from My side:-
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("input").click(function() {
$('<input type="text" name="name" value="value"/>').appendTo('#testdiv');
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div id="testdiv"></div>
<input type="button" value="Add" />
</body>
</html>
we can do it in more easy way like by adding a function on button and on click we call that function for append.
<div id="Content">
<button id="Add" onclick="append();">Add Text</button>
</div>
<script type="text/javascript">
function append()
{
$('<p>Text</p>').appendTo('#Content');
}
</script>
$(function () {_x000D_
$('#Add').click(function () {_x000D_
$('<p>Text</p>').appendTo('#Content');_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="Content">_x000D_
<button id="Add">Add<button>_x000D_
</div>
_x000D_
Running example:
//If you want add the element before the actual content, use before()_x000D_
$(function () {_x000D_
$('#AddBefore').click(function () {_x000D_
$('#Content').before('<p>Text before the button</p>');_x000D_
});_x000D_
});_x000D_
_x000D_
//If you want add the element after the actual content, use after()_x000D_
$(function () {_x000D_
$('#AddAfter').click(function () {_x000D_
$('#Content').after('<p>Text after the button</p>');_x000D_
});_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
_x000D_
<div id="Content">_x000D_
<button id="AddBefore">Add before</button>_x000D_
<button id="AddAfter">Add after</button>_x000D_
</div>
_x000D_
Source: Stackoverflow.com