1

I created a jsp which has a script that adds input boxex dynamically, the problem is I don't know how am I supposed to throw it on the servlet in order to save the data to the database from those dynamic input boxes. Please help me.

var i = 1;

<form id="add_pname" name="add_pname"><table class="table table-bordered" id="dynamic_field">
<tr>
 <td><select name="txtProduct" id="txtProduct" class="form-control        name_list" ><option value="">- Product -</option><%=obj.getProductOpt("")%></select></td>
</tr></table></form>

//adding input boxes

$('#add').click(function(){
    i++;
    $('#dynamic_field').append('<tr id="row'+i+'"><td><select name="txtProduct" id="txtProduct" class="form-control name_list" ><option value="">- Product -</option><%=obj.getProductOpt("")%></select></td><td><input type="text" name="txtQty" id="txtQty'+i+'" class="form-control"/></td><td><input type="button" name="remove" value="X" id="'+i+'" class="btn btn-danger btn_remove"/> </td></tr>');
});

//removing input boxes

$(document).on('click', '.btn_remove', function(){
    var button_id = $(this).attr("id");
    $('#row'+button_id+'').remove();
});

I want to pass all added input boxes to servlet and save it to the database. pelase help me

Marvs.M
  • 13
  • 7

1 Answers1

1

Well, there are different ways to solve that, let's describe two of them.

Client-side approach

I would add a submission handler to the form (submit="myHandler()"), where I would cycle through all the table rows, get the drop-down value (txtProduct) and the text value (txtQty), combine them into an object, add this object into an array, and afterwards send the array to the servlet, either via standard POST form submit (e.g. stringified as a hidden form field), or via AJAX call.

The servlet then needs to deserialize the data and create their Java representation to store it into the database.

Server-side approach

When adding the input fields dynamically, don't use the same name, but rather add a counter, so you will have table rows with txtProduct1 and txtQty1, then txtProduct2 + txtQty2, and so on. Then simply send the form to the servlet, using normal form submission.

The servlet then needs to iterate the request parameters (see e.g. https://stackoverflow.com/a/2595272/3511123) get all the txtProductX and txtQtyX parameters and their values, combine them (because thanks to that numbers it is clear which Qty belongs to what Product), and store into the DB.

Sorry for no code, but with code examples it would be an article / tutorial, not a simple answer. If you need some help with particular steps, feel free to ask a new question (after you do the obvious googling).

Jozef Chocholacek
  • 2,874
  • 2
  • 20
  • 25