Dynamically add rows in ASP.NET MVC table form
Change your
<button id="add" type="submit" class="btn btn-primary">Add</button>
into
<button id="add" class="btn btn-primary">Add</button>
I don't think Add
button should do a submit
.
Then remove src="~/bundles/jqueryval.js"
part from your script
tag. According to this answer, we should not leave src
attribute here.
Like this
<script type="text/javascript">
var counter = 1;
//... the rest of your code is here...
</script>
If you actually have a jqueryval.js
file, put it in another <script>
tag.
Here is the result you are expecting if I'm not mistaken.
var counter = 1;
$(function () {
$('#add').click(function () {
$('<tr id="tablerow' + counter + '"><td>' +
'<input type="text" class="text-box single-line" name="ClientSampleID[' + counter + ']" value="" required="required" />' +
'</td>' +
'<td>' +
'<input type="text" class="text-box single-line" name="AdditionalComments[' + counter + ']" value="" required="required" />' +
'</td>' +
'<td>' +
'<input type="text" class="text-box single-line" name="AcidStables[' + counter + ']" value="" required="required" />' +
'</td>' +
'<td>' +
'<button type="button" class="btn btn-primary" onclick="removeTr(' + counter + ');">Delete</button>' +
'</td>' +
'</tr>').appendTo('#submissionTable');
counter++;
return false;
});
});
function removeTr(index) {
if (counter > 1) {
$('#tablerow' + index).remove();
counter--;
}
return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<legend>Sample submission</legend>
<table id="submissionTable" class="table table-bordered">
<thead>
<tr>
<td>Sample ID</td>
<td>Additional Comments</td>
<td>Acid-stable amino acids</td>
</tr>
</thead>
<tr id="tablerow0">
<td>
<div class="editor-field">
<input class="text-box single-line" name="ClientSampleID[0]" type="text" value="" required="required" />
</div>
</td>
<td>
<div class="editor-field">
<input class="text-box single-line" name="AdditionalComments[0]" type="text" value="" required="required" />
</div>
</td>
<td>
<div class="editor-field">
<input class="text-box single-line" name="AcidStables[0]" type="text" value="" />
</div>
</td>
<td>
<button type="button" class="btn btn-primary" onclick="removeTr(0);">Delete</button>
</td>
<td></td>
</tr>
</table>
<p>
<button id="add" type="button" class="btn btn-primary">Add</button>
</p>
<hr />
<p>
<input type="submit" value="Create" class="btn btn-default" />
</p>
</fieldset>
Let me know if it helps.