Javascript: Form element values to a Collection - java

I have a HTML page with dinamycally changing number of select elements.
<script>
function getValues() {
var selects = document.getElementsByTagName('select'),
arr = Array.prototype.slice.call(selects),
selectValues = arr.map(function (select) {
return select.value;
});
return selectValues;
}
</script>
<script type='text/javascript'>
function moreSelect() {
for (i = 0; i < number; i++) {
// Append a node with a random text
container.appendChild(document.createTextNode("Name " + (i+1) + ": "));
// Create an <input> element, set its type and name attributes
var input = document.createElement("select");
input.name = "name" + (i+1);
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
</script>
<form action="action"method="POST" onsubmit="return getValues;">
More selects (max. 9):<br>
<p>
<input type="number" id="name" name="name" value="0"
min="0" max="9"><br />
<button type="button" onclick="moreSelect()">Add</button>
<br>
<p>
<br>
<div id="container" /></div>
<p>
<br> <br> <input type="submit" value="Go">
</form>
I want to collect this values to a List or an Array before the POST method and give this parameter list to my Java controller like this:
#RequestParam("allValues") List<String> allValues
Edit: I edited it, but doesn't works.

Get all selects, transform them to a real Array by Array.prototype.slice. Now you can use map to get all values. getElementsByTagName returns a HTMLCollection, that does not support map(), etc.
var selects = document.getElementsByTagName('select'),
arr = Array.prototype.slice.call(selects),
selectValues = arr.map(function (select) {
return select.value;
});
Now selectValues is an Array of the select values.

You can add one hidden form parameter say with name "allValues" and using javascript before posting Form, you can add all select values in that parameter.

Related

How to send dropdown value to servlet NOT the option text

I have dropdown with options and the values. I can get the option value by the dropdown name in servlet but how can i get the dropdown "value" in servlet. In screenshot, temporarily i concatenated the with options but i want to store value in variable in servlet.
Please help:
HTML:
<input type="text" name="taxiDropdown" id= "taxiDropdown" placeholder="Search taxi...">
</div>
<div class="scrolling menu">
<%
List eList = (ArrayList) session.getAttribute("taxiInfo");
%>
<%
for (int i = 0; i < eList.size(); i++) {
%>
<div class="item" data-value="<%=((TaxiInfo) eList.get(i)).getID()%>">
<div class="ui green empty circular label"></div>
<%=((TaxiInfo) eList.get(i)).getTaxiPlate() +" "+ ((TaxiInfo) eList.get(i)).getID() %>
</div>
<%
}
%>
</div>
</div>
Servlet:
String val = request.getParameter("taxiDropdown");
(in "val", I want to store the value of the dropdown not the option text)
In JSP you should have something like that:
<form method="post">
<select name="taxiDropdown" id="taxiDropdown">
<%
List<TaxiInfo> eList = (List<TaxiInfo>) request.getAttribute("taxiInfo");
for (TaxiInfo taxiInfo : eList) {
%>
<option name="<%=taxiInfo.getTaxiPlate()%>" value="<%=taxiInfo.getID()%>"><%=taxiInfo.getTaxiPlate()%></option>
<%
}
%>
</select>
<input type="submit" />
</form>
Then in controller/servlet you will receive the id of TaxiInfo:
String val = request.getParameter("taxiDropdown");
System.out.println(val);
Or in your case you should set a hidden input with javascript with desired value.
added this code in html:
Move value of the dropdown selection to hidden textbox
<script type='text/javascript'>
$(function() {
$('#driverdp').change(function() { <-- this is my dropdown -->
var x = $(this).val();
$('#driverid').val(x); <-- this is my textbox -->
});
});
</script>
Servlet:
get the value of hidden text in servlet
String text= request.getParameter("driverId");
hope it will help someone

Multiple checkbox checked value

I have written the following code in JSFiddle to able so get the sum of combined values of the checkboxes.
Script
var inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total');
for (var i=0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var add = this.value * (this.checked ? 1 : -1);
total.innerHTML = parseFloat(total.innerHTML) + add
}
}
Code
<input value="33" type="checkbox" class="sum" data-toggle="checkbox">
<input value="50" type="checkbox" class="sum" data-toggle="checkbox">
<input value="62" type="checkbox" class="sum" data-toggle="checkbox">
<span id="payment-total">0</span>
There it works perfect, when I implement this in my system there is no reslut or any error.
The checkboxes in my system are genarated by an MySQL output.
Any suggestions what migh be wrong?
Your code is probably running before the elements are dynamically generated, so the event handlers are not being attached. Try delegating the event handlers using .on() method:
$total = $('#payment-total');
$(document).on("click", ".sum", function() {
var add = this.value * (this.checked ? 1 : -1);
$total.text(function(i, value) {
return parseFloat(value) + add;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input value="33" type="checkbox" class="sum" data-toggle="checkbox">
<input value="50" type="checkbox" class="sum" data-toggle="checkbox">
<input value="62" type="checkbox" class="sum" data-toggle="checkbox">
<span id="payment-total">0</span>
I prefer to use pure javascript for your solution because you didn't use Jquery on your code. I think problem reason comes from Javascript eventListener. When you create a new element to your document, you should add its events.
In first code i create a checkbox but this is not work as others. link_1
<http://jsfiddle.net/3oweu107/1/>
However in second code i add event as other checkbox so payment-total value calculation done by new event. link_2
<http://jsfiddle.net/3oweu107/2/>
i hope this will help your problem :)

Passing Array from Jsp to action class

I need to pass my array of dynamically created objects from jsp to java action class , Meanwhile i am tring following code to set array objects as a request parameter for action form . But while fetching in action class it produce null result ,as array object are not passed on to action form. Kindly provide me a right way to pass array list to action class. Thanks in advance ////
<script>
var i;
var arraya = new Array();
var arrayb = new Array();
var arrayc = new Array();
var idCount = 1;
function arr()
{
for (var j=0;j<idCount;j++)
{
arraya[j]= document.getElementsByName("a"+j)[0].value;
arrayb[j]= document.getElementsByName("b"+j)[0].value;
arrayc[j]= document.getElementsByName("c"+j)[0].value;
}
var one=arraya.valueOf();
var two=arrayb.valueOf();
var three=arrayc.valueOf();
}
</script>
<input type="text" name="a0">
<input type="text" name="b0">
<input type="text" name="c0">
<input type="button" onclick="addDiv();" value="Add"/>
<input type="hidden" name="one" value="<%= request.getParameter("one") %>" />
<input type="hidden" name="two" value="<%= request.getParameter("two") %>" />
<input type="hidden" name="three" value="<%= request.getParameter("three") %>" />
You can achieve it by doing this -
Simply have input type like this. Notice no index used.
<input type="text" name="a"/>
<input type="text" name="b"/>
<input type="text" name="c"/>
In your action class you can then do this. The values will be in the order.
String[] a = request.getParameterValues("a");
String[] b = request.getParameterValues("b");
String[] c = request.getParameterValues("c");
Although since you are using Struts you should actually create an object having properties a, b and c. Use the object in array fashion.

Set a checkbox in Javascript dynamically

Can someone please tell me how to set a checkbox dynamically in Javascript?
function displayResults(html){
var v = html.split(",");
document.getElementById('fsystemName').value = v[0];
if (v[1] == "true"){
document.getElementById('fUpdateActiveFlag').checked = true;
}
}
So I am passing some values from my controller separated by commas. For the checkbox, when the value is true I want it to tick the box.
EDIT:
When a value is changed from a dropdown box it calls this displayResults method as its return statement:
$('#uINewsSystemList').change(function() {
$.get("/live-application/SystemById", {systemid: $("#systemList").val()}, displayResults, "html");
I want it to update some other values such as textboxes and checkboxes. I can get the fsystemName to populate with the appropriate value but the fUpdateActiveFlag always stays unchecked.
In your question, you posted a javascript example, not JSP.
In JSP you can use a for loop to write the checkbox like this:
<% for (Element element : elementList) { %>
<input type="checkbox" name="<%=element.getName() %>" value="<%=element.getValue() %>" <%=element.getChecked() ? "checked" : "" %> />
<% } %>
Will result in:
<input type="checkbox" name="option1" value="Milk"> Milk<br>
<input type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input type="checkbox" name="option3" value="Cheese"> Cheese<br>

Change Value Of A Field On Submit Using Javascript

I would like to add some JavaScript to do the following.
I would have 3 fields like this.
<input type="text" name="a" />
<input type="text" name="b" />
<input type="hidden" name="c" />
say if I entered 100 in the first field and 19 in the second field.
it would divide 100 by 19 and round it up to no decimal places, and then replace the value of the third hidden field by the answer, so in the case it would be (100/19) 5.26... rounded up to 6
however I am not sure how to actually implement this.
Say your form looks like this;
<form id="myForm" method="POST">
<input type="text" name="a" />
<input type="text" name="b" />
<input type="hidden" name="c" />
</form>
You can access the form like this;
function doAction(action)
{
var frm = document.forms.myForm;
frm.c.value = frm.a.value/frm.b.value;
}
You can trigger the action by adding a button that can be clicked, or setting the form's submit action.
Edit: Doesn't round up, not sure how to do that :(
A nice easy method is to pass the form to a function, and allow that function to do the calculation.
The form should look like:
<form>
<input type="text" name="a" />
<input type="text" name="b" />
<input type="hidden" name="c" />
<input type="button" value="Click" onClick="doCalculate(this.form)" />
</form>
and the javascript:
function doCalculate(theForm){
var aVal = parseFloat(theForm.a.value);
var bVal = parseFloat(theForm.b.value);
var cVal = 0;
if(!isNaN(aVal) && !isNaN(bVal)){
cVal = Math.ceil(aVal/bVal);
}
theForm.c.value = cVal;
}
Working example here --> http://jsfiddle.net/azajs/
Edit: This can also be done when the form is submitting by having a similar call in the onsubmit of the form:
<form onsubmit="doCalculate(this);" >
...
</form>
A dumbed-down way, which assumes your form is document.forms[0]:
<input type="text" name="a" onchange="myFunction" />
<input type="text" name="b" onchange="myFunction" />
<input type="hidden" name="c" />
function myFunction() {
var inpA = document.forms[0].a;
var inpB = document.forms[0].b;
var aVal = parseFloat(inpA.value);
var bVal = parseFloat(inpB.value);
if (!isNaN(aVal) && !isNaN(bVal) && bVal !== 0) {
document.forms[0].c.value = Math.ceil(aVal/ bVal);
}
}
EDIT: Math.round => Math.ceil
After the form elements:
<script type="text/javascript">
(function() {
var a= document.getElementsByName('a')[0];
var b= document.getElementsByName('b')[0];
var c= document.getElementsByName('c')[0];
a.onchange=b.onchange=a.onkeyup=b.onkeyup= function() {
c.value= Math.ceil(a.value/b.value);
};
})();
</script>
This recalculates on each key press, remove the keyup binding if you don't want that.
Add a unique id to each input and use document.getElementById to avoid any ambiguity with name. If this form is never going to be submitted you can omit name entirely.
Math.ceil() will return NaN if either value cannot be read as a number, or Infinity if you divide by zero. You may wish to check for these conditions and write a different value.
You do this by binding an eventlistner to the from element. You either create your own (Javascript native event handlers) or use your favorit javascript framework. My example is for using the jQuery jQuery bind method javascript framework.
/* first set and id to your input hidden and form element so you can reach it in fast way */
<form id="myForm"><input type="hidden" id="total" name="c" /></form>
/* Javascript code using jquery */
$('#form').bind('submit', function () {
$('#total').val(function () {
var num = parseFloat($('#form input[name=a]').val()) / parseFloat($('#form input[name=b]').val());
return Math.floor(num) === num ? num : Math.floor(num) + 1;
});
});

Categories

Resources