I’m using the following script to dynamically add and delete fields to a card within a form. I’m trying to pass the values to my model binding property, which is a List<ushort>
<div style="width:40%;">
<div class="">
<div class="col-lg-12">
<div id="row">
<div class="input-group m-3">
<div class="input-group-prepend">
<button class="btn btn-danger"
id="DeleteRow"
type="button">
<i class="bi bi-trash"></i>
Delete
</button>
</div>
<input type="text" class="form-control m-input">
</div>
</div>
<div id="newinput"></div>
<button id="rowAdder" type="button" class="btn btn-dark">
<span class="bi bi-plus-square-dotted">
</span> ADD
</button>
</div>
</div>
</div>
<script type="text/javascript">
$("#rowAdder").click(function () {
newRowAdd =
'<div id="row"> <div class="input-group m-3">' +
'<div class="input-group-prepend">' +
'<button class="btn btn-danger" id="DeleteRow" type="button">' +
'<i class="bi bi-trash"></i> Delete</button> </div>' +
'<input type="text" class="form-control m-input"> </div> </div>';
$('#newinput').append(newRowAdd);
});
$("body").on("click", "#DeleteRow", function () {
$(this).parents("#row").remove();
})
</script>
I’ve tried using a hidden field bound to the model property and updating the field on submit to an array.
function updatePortsInput() {
console.log("updatePortsInput called");
var ports = [];
$(".m-input").each(function () {
var portValue = parseInt($(this).val());
if (!isNaN(portValue) && portValue >= 0 && portValue <= 65535) {
ports.push(portValue);
}
});
$('[name="Ports"]').val(JSON.stringify(ports));
}
<input type="hidden" id="portsInput" name="Ports" asp-for="Ports" />
But I’m unable to populate my List with the values of the generated fields.
Does someone have an idea on this?