I have a form which has multiple input fields that will be added dynamically when user click the Add button.
I already managed to achieve this, but the problem I am facing now is I cannot pass the parameters that has been added dynamically using JavaScript function, to a servlet.
This is the code of dynamically adding multiple input fields:
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addDynamicDivs").click(function () {
var newTextBoxDiv1 = $(document.createElement('div'))
.attr("id", 'TextBoxDiv1');
newTextBoxDiv1.attr("style",'float: left;');
var newTextBoxDiv2 = $(document.createElement('div'))
.attr("id", 'TextBoxDiv2');
newTextBoxDiv2.attr("style",'float: left;');
var newTextBoxDiv3 = $(document.createElement('div'))
.attr("id", 'TextBoxDiv3');
newTextBoxDiv3.attr("style",'float: left;');
var newTextBoxDiv4 = $(document.createElement('div'))
.attr("id", 'TextBoxDiv4');
newTextBoxDiv4.attr("style",'float: left;');
newTextBoxDiv1.after().html('<label class="inputlabel2">Speaker Name : </label>' +
'<input type="text" name="speakername" id="speakername" value="" >');
newTextBoxDiv2.after().html('<label class="inputlabel2">Speaker Country : </label>' +
'<input type="text" name="speakercountry" id="speakercountry" value="" >');
newTextBoxDiv3.after().html('<label class="inputlabel2">Speaker Company : </label>' +
'<input type="text" name="speakercompany" id="textbox" value="" >');
newTextBoxDiv4.after().html('<label class="inputlabel2">Speaker Desc : </label>' +
'<textarea name="speakerdesc" id="speakerdesc" rows="10" cols="30" ></textarea>');
newTextBoxDiv1.appendTo("#TextBoxesGroup");
newTextBoxDiv2.appendTo("#TextBoxesGroup");
newTextBoxDiv3.appendTo("#TextBoxesGroup");
newTextBoxDiv4.appendTo("#TextBoxesGroup");
});
});
</script>
It appears that the only parameters passed to the servlet are from the form, not including the parameters from the dynamically added input fields.
How can I pass all the parameters from the function to the servlet?
Thanks,
raz
You have to include the dynamic params inside the form. You should put inside the form the div elemt where you are including the dynamic params.
<form>
<div id="TextBoxesGroup">
</div>
</form>
Related
Here I am creating dynamic table inside jQuery by using AJAX call. In this table I am creating select box. But I have to provide the dynamic values to that select box, so I am using the id of that select box and appending the data inside it.
But I am not able to solve the issue.
Qualification.js
function switchOption() {
var selectedValue= $("#companyClass").val();
$.ajax({
type: "GET",
url: "getClass",
data:'classId='+selectedValue,
success: function(data){
var tablebody = $('<tbody>');
var tablerow = "";
$(data.qualAttributes).each(function(index){
tablerow = $('<tr>')
.append($('<td>').append($('<input>').attr({type :'checkbox'}).attr('class','checkBoxSize').attr({value : ''+$(this)[0].qualId}).attr('id','attributeList').attr('name','attributeList')))
.append($('<td>').append($(this)[0].qualAttrName+''))
.append($('<td>').append($('<select>').attr('class','form-control').attr('id','operatorList').attr('name','operatorList')))
.append($('<td>').append($('<input>').attr({type :'text'}).attr('class','form-control').attr('id','attributeValue').attr('name','attributeValue')))
.append($('<td>').append($('<input>').attr({type :'hidden'}).attr('class','form-control').attr('id','attributeValueHidden').attr('name','attributeValueHidden').attr('value',$(this)[0].qualId)))
$(tablebody).append(tablerow);
});
$(data.operatorList).each(function(i,value){
$('#operatorList1').append($('<option>',
{
value: value.dropdownId,
text : value.dropdownValue,
}));
});
Portion of Qualification.jsp
<div class="form-group">
<label class="label-bg col-xs-12">Class <span class="red">*</span></label>
<div class="col-xs-12">
<form:select id="companyClass" class="form-control" path="companyClass" onchange="switchOption();">
<form:option value="Select" />
<form:options items="${classList}" itemValue="id" itemLabel="dropdownValue"/>
</form:select>
</div>
</div>
Note: there are no errors in the log. If I print value.dropdownId in console it is giving correct value.
Is it possible that while defining select in jQuery, can I append the values by using like this?
$(data.operatorList).each(function(i,value){
$('#operatorList1').append($('<option>',
{
value: value.dropdownId,
text : value.dropdownValue,
}));
});
I am working in spring mvc, I used the following line to generate the checkboxes from DB table.
<td><input type="checkbox" name="loanId" value="${loan.id}" class="it"></td>
I need to get the index of this selected values in my java controller. I am able to get the values which are selected, but how to get the index values?
following code is I am using
String[] loanIds = request.getParameterValues("loanId");
for (String string : loanIds) {
System.out.println("loanIds****"+string);
}
You need javascript to get the index of checkbox and set it to hidden field :
var ids = document.getElementsByName('loanId');
var ind = document.getElementById('loanIndex');
var put = function() {
var arr = [];
var i = -1;
while (ids[++i])
if (ids[i].checked) arr.push(i);
ind.value = arr.join(',');
alert('selected index: ' + ind.value);
};
var i = -1;
while (ids[++i])
ids[i].onchange = put;
<input type="checkbox" name="loanId" />
<input type="checkbox" name="loanId" />
<input type="checkbox" name="loanId" />
<input type="checkbox" name="loanId" />
<input type="hidden" name="loanIndex" id="loanIndex" value="" />
In controller:
String[] loanIndex= request.getParameter("loanIndex").split(",");
There is no direct method for this purpose.
You can have index as value which is passed on selecting checkbox. You can use this index-value later to get selected record data from in-memory collection i.e. when user selects checkbox and submits request, on server side you will fetch ParameterValues from request and list data from datasource, compare ids then derive selected list.
Using Jquery
var indexString;
var index;
$('#.it').each(function () {
$(this).find('.SomeCheckboxClass').each(function () {
if ($(this).attr('checked')) {
index = $(this).index();
indexString = index + ",";
}
});
});
post this indexString, it is a comma separated index string.
I am making a web application in which I pass a Int value from a servlet to next jsp page like this :
request.setAttribute("n",n);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/sharingfilesselection.jsp");
dispatcher.forward(request, response);
Now on the next page i.e sharingfilesselection.jsp I want that n textboxes are created dynamically each with a different id as i need to store the values of these textboxes in my database.
The N is obtained on next jsp page by this :
Object N=request.getAttribute("n");
How this can be done using javascript ?Please help
You can do this using JSTL:
<c:forEach var="i" begin="1" end="${n}">
Input ${i}: <input type="text" name="txtDynamic_${i}" id="txtDynamic_${i}" />
<br />
</c:forEach>
Try this in your
.javascript
<%String n=(String)request.getAttribute("n");%>
var n=<%=n%>;
for(var i=0;i<n;i++{
$(".exac").append("<input type="text" id='textbox"+i+"'></input>");
}
}
.html
<div class="exac">
</div>
Working sample here
html
<div id="container"><input type="button" onclick="createTextBox(5)" value="create textbox">
JS
function createTextBox(n) {
for (var i = 0; i < n; i++) {
var textBox = document.createElement("input");
textBox.setAttribute("id", "text_" + i);
document.getElementById("container").appendChild(textBox);
}}
I have created dynamic row on click of button in table using following code :
<script type="text/javascript">
var counter = 1;
function displayResult()
{
counter++;
document.getElementById("myTable").insertRow(-1).innerHTML = '<td><select name="list_dispatch_state" id="list_dispatch_state"><option value="01">01</option><option value="02">02</option><option value="03">03</option></select></td><td><input type="text" name="txt_email'+ counter +'" id="txt_email'+ counter +'" value='+ counter +'></td>';
}
</script>
<body>
<form action="Dogetdat" method="post">
<table id="myTable" border="1">
<tr>
<th>Select</th>
<th>Value</th>
</tr>
</table>
<br />
<button type="button" onclick="displayResult()">Insert new row</button>
<input type="submit">
</form>
</body>
my question is that, on click of button new row and control inside it created but when I click on submit then form submitted to servlet page.
Then how servlet will know that how many data are received ?
Because in servlet I ll get data using
String str1= request.gerParameter("txt_email");
how servlet will know that how many variable it have to create and what will be the name of that ? what will I have to pass in request.gerParameter(""); ?
You have to use the following request.getParameterValues and get the result as an array
String emails[] = request.getParameterValues("txt_email");
I have a form having fields like:
<div class="row">
<div class="field">
<input class="" type="text" name="college" id="college"/>
</div>
<div class="field">
<input class="" type="text" name="city" id="city"/>
</div>
<div class="field">
<input class="" type="text" name="zip" id="zip"/>
</div>
</div>
<input type="button" class="buttonWidth" id="btnAddressAdd" value="Add Worksite Addressess"/>
I have a Add extra address button that add's another copy of div "row" to the page. I need to send all data from the page as a request to the Controller. How do I write a script that add's extra div copy onclick of the button and also appends a unique id to each of the new fields?
See working example in Dojo: http://jsfiddle.net/phusick/PeQCN/
And the same code in plain vanilla JavaScript: http://jsfiddle.net/phusick/Rceua/
The Dojo version employs dojo/_base/lang::clone as #Peter Rader mentioned:
// var lang = require("dojo/_base/lang");
// var array = require("dojo/_base/array");
// var query = require("dojo/query");
// var domAttr = require("dojo/dom-attr");
var counter = 0;
function duplicate(/*Node*/sourceNode, /*Array*/attributesToBump) {
counter++;
var out = lang.clone(sourceNode);
if (domAttr.has(out, "id")) { out.id = bump(out.id); }
query("*", out).forEach(function(node) {
array.forEach(attributesToBump, function(attribute) {
if (domAttr.has(node, attribute)) {
domAttr.set(node, attribute, bump(domAttr.get(node, attribute)));
}
})
});
function bump(/*String*/str) {
return str + "_" + counter;
}
return out;
}
How to use the aforementioned duplicate function:
// var dom = require("dojo/dom");
// var domConstruct = require("dojo/dom-construct");
var sourceNode = dom.byId("fieldset");
var node = duplicate(sourceNode, ["id", "name", "placeholder"]);
domConstruct.place(node, sourceNode, "after");
I have written code to achieve this.
Logic:
1) get the innerHTML of desired parent
2) replace id in the text
3) Insert the new html
See a working code
Pardon me for bad style of coding on JS part. I am not use to coding directly on DOM. I prefer JQuery.
Try
to use this snipplet (see usage)
http://dojotoolkit.org/reference-guide/1.8/dojo/_base/lang.html#dojo-base-lang-clone