Dynamically adding duplicate (unique ID) form Div elements using javascript - java

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

Related

Pagination issue with JSP

I am able to display a table when a user clicks a search button. But now I want to split the table into chunks of 20 rows where the user can click next or previous to go forward and backward through all of the data. I am not allowed to use JavaScript for this assignment. Only JSP, Java, HTML.
The two debugging out.print() calls are not showing up. A different page is being loaded after one of the buttons is clicked, but the two debugging out.print calls are not displaying any HTML. I have checked out How to know which button is clicked on jsp this post but had no luck.
<form method="GET">
<center>
<input type="submit" name="previous_table" value="Previous" />
<input type="submit" name="next_table" value="Next" />
</center>
</form>
</br>
<%
String val1 = request.getParameter("previous_table");
String val2 = request.getParameter("next_table");
try {
if ("Previous".equals(val1)) { // Get previous results
out.println("<h1>HELLO 1</h1>");
buildTable(rs, out, false);
}
else if ("Next".equals(val2)) { // Get next results
out.println("<h1>HELLO 2</h1>");
buildTable(rs, out, true);
}
} catch(Exception e) {
out.print("<center><h1>"+e.toString()+"</h1></center>");
}
%>
I also have a follow up question. If the user clicks next or previous button, will my current table on the page be overwritten by the new one? That is my intent but I don't know if it will work that way.
I WAS ABLE TO FIX IT BY DOING THIS:
<form method="POST">
<center>
<input type="submit" name="previous_table" value="Previous" />
<input type="submit" name="next_table" value="Next" />
</center>
</form>
</br>
<%
String val1 = request.getParameter("previous_table");
String val2 = request.getParameter("next_table");
you should add name with value for button after that you can get by parameter click value.
`<input type="hidden" name="myprevious" value="previous"/>
<input type="hidden" name="mynext" value="next" />
<%
String val1 = request.getParameter("myprevious");
String val2 = request.getParameter("mynext");
try {
if (val1 == "previous") { // Get previous results
out.println("<h1>HELLO 1</h1>");
buildTable(rs, out, false);
}
else if (val2 == "next") { // Go next results
out.println("<h1>HELLO 2</h1>");
buildTable(rs, out, true);
}
} catch(Exception e) {
out.print("<center><h1>"+e.toString()+"</h1></center>");
}
%>
`
I hope it will help you.
Thanks.
Try to use the subList() method of a List<>().
As explained here.
HOW TO IMPLEMENT IT ##
you can put an hidden input in your form to give you the last index for your list like :
<input type="hiden" value="${last_index_of_your_list + 1}" name="index">
Then in your servlet part you put like this :
int index = Interger.ParseInt(request.getParameter("index"));
if(index <= 0){
datalist = datalist(0, 19>datalist.size()? datalist.size() : 19);
}else{
if(clicked_on_next){
datalist = datalist(index, index+19>datalist.size()? datalist.size() : index+19 );
}else{
datalist = datalist(index - 40, index-20>datalist.size()? datalist.size() : index-20 );
}
}
You are using hidden fields but you need to use submit button for next and previous.
<input type="submit" name="myprevious" value="previous"/>
<input type="submit" name="mynext" value="next" />
Make sure both are define in form. when we submit form after that you will get button value in parameter.same my previous answer. because we can not get parameter value without submit form.
Thanks.

Selecting an html element that is loaded after documents loads, using selenium find element by xpath to select the element

How my web application works:
My web application loads a div with radio button input elements after conditions in the form above are changed. The form above will allow the manager to select a date and time. The div below will load with all the employees available at that date and time. I give this div the id "EmployeeListBox". Everytime conditions change in the form above the EmployeeListBox gets radio buttons injected using jquery's append method.
Okay so that's the idea of how my web application works. What I am trying to do is click the first radio button in the div EmployeeListBox after the form gets changed, using selenium web driver for Firefox in java. This is the line that I need to fix:
`driver.findElement(By.xpath("//[#id="EmployeeCell"]/span[2]/input")).click();`
When I run this xpath I recive this error:
Exception processing script - Element not found in the cache - perhaps the page has changed since it was looked up.
I guess the xpaths I have tried do not work because the elements are dynamically loaded.
Here is the JS code that loads the EmployeeListBox.
AvialableStaff = JSON.parse( data );
var MSG = "";
$('#EmployeeListBox').empty();
/*for each employee in AvialableStaff load the #CreateShiftLifeOfEmployees Select option*/
var eico = 0;
for ( var Staff in AvialableStaff )
{
var ID = AvialableStaff[Staff]["employeeID"];
var name = AvialableStaff[Staff]["Firstname"]+" "+ AvialableStaff[Staff]["Lastname"];
MSG += "<div id = \"EmployeeCell\">";
MSG += "<span class = \"MakeLeft\" id = \"EI"+eico+"\" > "+name+" </span>";
MSG += "<span class = \"MakeRight\"><input type = \"radio\" name=\"ChooseStaff\" value = \""+ID+"\" class = \"CSTAFFradioButtons\" /> </span>";
MSG += "</div>";
eico++;
}
$('#EmployeeListBox').append( MSG );
Here is my EmployeeListBox without the employee cells:
<p>Select an available employee</p>
<div id = "CSEmployeeList" >
<div id = "StaffAvaileP"> <h3> Staff Available</h3> </div>
<div id = "EmployeeListBox">
<!-- Radio Buttons go here -->
</div>
</div>
This is what the employee box looks like after the form has been changed and employee radio buttons have been inserted:
<div id="EmployeeListBox">
<div id="EmployeeCell">
<span class="MakeLeft" id="EI0"> Person One </span>
<span class="MakeRight">
<input type="radio" name="ChooseStaff" value="9" class="CSTAFFradioButtons">
</span>
</div>
<div id="EmployeeCell">
<span class="MakeLeft" id="EI1"> Person Two </span>
<span class="MakeRight">
<input type="radio" name="ChooseStaff" value="10" class="CSTAFFradioButtons">
</span>
</div>
<div id="EmployeeCell">
<span class="MakeLeft" id="EI2"> Person Three </span>
<span class="MakeRight">
<input type="radio" name="ChooseStaff" value="11" class="CSTAFFradioButtons">
</span>
</div>
</div><!--End of EmployeeListBox -->
Here is my java method which runs the test:
/** Method testCreateShifts
* purpose: Loads shifts with realistic shift data like the
* real life Saturday schedule.
*/
public static void testCreateShifts()
{
driver.get(theurl);
String createshiftPage = "https://***/index.php?/CreateAShift";
driver.get(createshiftPage);
new Select(driver.findElement(By.id("Day"))).selectByVisibleText("11");
new Select(driver.findElement(By.id("StartTime"))).selectByVisibleText("8:30am");
new Select(driver.findElement(By.id("EndTime"))).selectByVisibleText("2:00pm");
driver.findElement(By.id("Instructor")).click();
/*TODO: Currently trying to click on first employee in employee list box*/
driver.findElement(By.xpath("//*[#id=\"EmployeeCell\"]/span[2]/input")).click();
driver.findElement(By.id("CreateShiftSubmit")).click();
}/*End of Method testCreateShifts*/
So using selenium in java how do I click first radio button that is in the list after the EmployeeListBox gets reloaded by jquery?
I found out what was wrong. I needed to give my webapplication time to load.
I told my java test to wait 1 second with this line.
try {Thread.sleep(2000);}catch (InterruptedException ex) { }

How would I do an Angular JS ng-repeat on this JSON parse?

How would I do an Angular JS ng-repeat on this JSON parse?
.controller('TeamsCtrl', function($scope) {
var text = '{"employees":[' +
'{"name":"John Doe"},' +
'{"name":"Sam Doe"},' +
'{"name":"Jack Doe"}]}';
/* create scope property that will be recognized in view*/
$scope.tasks = JSON.parse(text);
});
Here is the area I want populated with the new content:
<ion-content class="has-header" ng-controller="TeamsCtrl">
<div class="list card" ng-repeat="employee in tasks.employee" ng-click="showActionsheet()">
<div class="item item-divider">
<div>{{employee.name}}</div>
</div>
You aren't assigning the parsed results to a scope variable
Controller should be more like:
.controller('TeamsCtrl', function($scope) {
var text = '{"employees":[' +
'{"name":"John Doe"},' +
'{"name":"Sam Doe"},' +
'{"name":"Jack Doe"}]}';
/* create scope property that will be recognized in view*/
$scope.tasks = JSON.parse(text);
});
Then in markup you can do something like:
<div ng-repeat="employee in tasks.employees">
<div>{{employee.name}}</div>
</div>
DEMO
You already have the Json object all you need is to set it in the scope and iterate over it
.
<h3>Output:</h3>
<div ng-app ng-controller="MyCtrl">
<ul>
<li ng-repeat="(id,emp) in items">{{id}}: {{emp.name}}</li>
</ul>
</div>
Js Fiddle here
If you are having correct list of employees than you can use like
<div ng-repeat="employee in employees>
<div>{{id}}:{{employee.name}}</div>
</div>
<div ng-repeat="item in obj.employees">{{item.name}}</div>
Check my plunker

Pass parameters from dynamically added input fields to servlet

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>

Creating Multiple textboxes dynamically

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);
}}

Categories