dynamically creates input box inside jsp and send to servlet - javascript

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

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).

Related

How to make multi choose autocomplate and how to send data?

Hi i use w3schools autocomplate tutorial. Link https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_autocomplete
I want to make multi choose. For example ; France and England for Country. Actually i saw multi choose example on Javascript but i need a variables. When i click send button my query executed so i need variables.
How can i do it ? and how can send value from input area to sql query ?
Image
It is difficult to understand what you're looking for in the way you phrased the question, but I will try answer based on how I understood the question.
First, I would add hidden input to contain array values under input ID: #myInput.
Try the following:
<input id="countries" type="hidden" value="countries[]" />
<input type="button" value="add" onclick="addCountry">
As you see, I bind click event to the button so function would be:
function addCountry(){
const countries = document.querySelector('#countries');
const country = document.querySelector("#myInput");
countries.value = [...countries.value, country.value];}
So, when you submit form, you will be able to get this from a PHP file
with []
$countries = $_POST['countries'];
Alternatively you can use $_GET instead.

Getting the value of an input field, which gets dynamically placed (not via js) onclick

I spent a few hours searching and trying stuff out, but I can't get my ajax form submit working. (I'm also really not a front-end person, so sorry if I mess up my explanation)
I have a site that dynamically inserts HTML content (through JSP, not javascript). I have a simple form with a submit button inside that inserted html. This is the piece of html I have:
<tr>
<td>Change stock by:</td>
<td>
<div id="quantityinput" class="field has-addons">
<div class="control"> <input class="input" type="text" id="mutation" placeholder="0">
</div>
update
</div>
</td>
</tr>
I managed to link the button to the right ajax-function, like this:
(.editor__product is the direct parent of the form, but there is a bunch of non-form information there)
$(".editor__product").on("click", "#quantityConfirm", function ($) {
$.ajax({
method: "POST",
url: '/bullet-journal/mutateitem',
data: {
product_id: product_id,
product_mutate: product_mutate
}
})
.done(function (html) {
$('#main').load(document.URL + ' #main');
$(".editor__product").load('${pageContext.request.contextPath}/refreshinfo');
});
});
But the problem is, I have no idea how to get the value from my "#mutation" input field. I tried various ways to append it to my document and get it, but it either results in a new text field somewhere on the bottom of my page, or simply in a NULL value error. I have more ajax forms in the website which work fine, but they use elements that are hardcoded.
Every solution I could find was specifically for javascript-generated content, while my input doesn't get generated by javascript.
How would I go about extracting the value from my mutation input? Thanks a lot for any advice, the browser console isn't very helpful.
Get the value using js :
var mutation = document.getElementById('mutation').value;
or with jquery
var mutation = $('#mutation').val();
And pass mutation in your data or do what you need to with it

Create dynamic HTML form using javascript

I've been googling and googling but completely stuck on this.
I have a GET request that retrieves some JSON containing a list of users. However the list of users changes.
I want to generate a simple HTML form that contains the names of the users, and then an input field so that they can be given a rating. I then need to gather the ratings and send a POST request in JSON.
What would be the best way to approach this? I was thinking of looping through the users and just displaying them with a text input type but then I have no idea how I can use the form data to send the POST request!
Any help would be greatly appreciated
Populate UI base on JSON
HTML:
<form id="user_list">
<div>
</div>
<input type="submit"/>
</form>
JS:
var obj = {
users:[{name:"user 1"},{name:"user 2"}]
}
var user_list = $("#user_list>div");
obj.users.forEach(function(user,index){
user_list.append("<div>"+
"<h1>" + user.name + "</h1>"+
"<input type='text' id='user_"+ index +"'/>"+
"</div>");
});
Send selected values to server.
Option 1
If you make this page full post back when click on submit, you have to change text boxes as following
"<input type='text' name='[user_"+ index +"]'/>"+
In server request object, you will be give as array of key/values.
Option 2
If you are planing to make AJAX request, again you can loop though the text boxes and build the JSON format which you want in back-end and pass though the AJAX.
$("input[type='text']").each(function(input){
$(input).val();
});

How can i get element by id in node.js

How can i get element id: <input type="number" name="1" id="cant1" style="width:60px;" required/> in node.js?
Actually i've got this: var cant = req.param("cant1"); but i get the name's input and i need the id.
Thanks for help me.
The ID is only used client side. The name is used to generate the form data that is sent to the server.
If you need the ID then you'll need to encode it in the form data somehow. Possible approaches include:
Just using that value as the name instead of 1
Using JavaScript to copy the ID value on top of the name or the value when the form is submitted
Generate a set of hidden inputs that map the name and id values (e.g. <input name="the_id_for_1" value="cant1">)
Generate some complex data structure in JSON and post it with Ajax instead of using a regular form submission

JavaScript n PHP w/ Select Boxes

Example is here.
I'm moving countries from one select box to another, when I submit the form I want the values in the right text box to be used by php. When I give the right box a name for a php array, like ToLB[] the Javascript fails. How can I handle this so that the submitted values will be used by php processes?
in forms it's a typical process to use an action and a method. This is declared within the form tag. For example
<form name='phpSend' method='post' action='myActions.php'>
Now when your form is submitted it is instantly 'posted' to the url myActions.php and is automatically declared as a $_POST array.
The names of the inputs become the array keys and the value becomes the value.
A basic method is to do a procedural action. Meaning if you leave the action attribute blank, the action will submit the form to the page you're already on and use if statements to check if the form has been submitted.
if(isset($_POST)&&isset($_POST['someName'])){
//form submitted!
}
Now, I've never used a multiple select before so you may want to var_dumb() or print_r() your output to double check but my guess is it'll be an Array within the $_POST array.
Submitting with javascript
if(document.getElementByName('phpSend').submit){//or however your checking
var selected=[];
for(var e=0;e<document.getElementByTagName('select').options.length;e++){
if(document.getElementByTagName('select').options[e].selected==true)selected[e]=document.getElementByTagName('select').options[e].value;
}
//then add the selected array to your preferred method of sending your data to your php document
}
I often encounter a situation like this and I usually submit the select options as a string.
Add an hidden field to your form:
<input type="hidden" name="valuesToSubmit">
<script type="text/javascript">
var selectobject=document.getElementById("myselect");
var myValues = "";
for (var i=0; i<selectobject.length; i++){
myValues = myValues + selectobject.options[i].value + ",";
}
document.form.valuesToSubmit.value=myValues;
</script>
In the PHP scripts that receive the posting data you can use the explode function to turn your sting into an array and then iterate on it ... depends what you need to do. Remember to remove the last unwanted ","
I have taken a look at your code.
There are some missing parts and amendments to do to make it works.
I didn't test the amendments but I think they should work.
1)you have to add the hidden field inside the form.
<form name="combo_box" action="test.php">
<input type="hidden" name="valuesToSubmit" value="">
2)Then you have to give the id to the select box because you use the id to reference the object like this var selectobject=document.getElementById("ToLB");
<select multiple size="10" name="ToLB" id="ToLB" style="width:150">
3)Change th submit button with a normal button so you can force the submit only when the loop is ended and the values have been passed into the hidden field.
<input type="button" name="submit" id="submit" value="Submit" onClick="updateValues()">
4)Force the submit at the end of the javascript
function updateValues(){
var selectobject=document.getElementById("ToLB");
var myValues = "";
for (var i=0; i<selectobject.length; i++){
myValues = myValues + selectobject.options[i].value + ",";
}
document.form.valuesToSubmit.value=myValues;
document.combo_box.submit();
}

Categories