Reputation: 5327
I have an add button, It adds html sections dynamically like so, Jsfiddle
var scntDiv = $('.wrapper');
var i = $('div.row').length;
$(".add_member").click(function () {
$('html goes here').appendTo(scntDiv);
})
The add was okay but I'm asked to keep making the html bigger, and I have to use it in different projects. So adding html elements inside append sucks plus you have to make it one liner and to substitute double quotes for single quotes.
I used knockoutJS and riotJS, both work perfectly but I don't want to add another library just to add sections without writing html.
Is there a way to make add an entire section in jquery or Js that is just as simple as the remove method? without having to write html manually?
Upvotes: 2
Views: 274
Reputation: 14927
Here's a possible solution based on your fiddle, without changing anything else (some things are wrong/clumsy with this code, see below):
// Clone the first entry (since it's always here and without a remove button)
var entry = $('#p_scents p:first').clone();
// Find the input with ID p_scnt, change its name, empty its value
entry
.find('#p_scnt')
.attr('name', 'p_scnt_' + i)
.val('');
// Append a remove button to it and append it to the wrapper div
entry
.append('<a href="#" id="remScnt">Remove</a>')
.appendTo(scntDiv);
Some notes looking at your fiddle though:
p_scnt
. This is invalid HTML, even though it "works" here..live()
is deprecated. You should use .on
on the closest wrapper instead. Check the docs.name
attribute doesn't have to be dynamic. You could just have it as p_scnt[]
and its values would be sent as an array. If you really need to specify an index, use p_scnt[i]
.Upvotes: 1
Reputation: 1790
you could possibly use an include with jquery:
<div id="include"></div>
<script>
$(function () {
$("#include").load("include.html");
});
</script>
Upvotes: 1