Pass some checkbox values from one JSP to another - javascript

I've been having problems passing parameters from one .jsp to another.
I have two .jsp (1 and 2). In 1 I get some data from a database and show the user a bunch of checkboxes (depending on the data I got before). The user has to check one or more of the checkboxes, the selected will be deleted in my database in 2. (It´s something like "Select the numbers you want to delete").
I don't know how to pass the selected checkboxes and the value from 1 to 2.
I tried with javascript/jQuery, trying to know if a checkbox is checked and its value, add the value to a hidden field and use the request in 2 to get it.
1.jsp
<%
HttpSession sesion = request.getSession();
Company company = (Company) sesion.getAttribute("company");
List<Phone> phones = company.getTelefonos();
%>
<form id="formulario" method="POST" action="desMul_Final.jsp">
<fieldset>
<legend>Numbers</legend>
<%
Iterator<Phone> it1 = phones.iterator();
while(it1.hasNext()){
Phone t = it1.next();
String number = t.getNumero();
%>
<p>
<input name=check id="t_<%=number%>" type=checkbox value="<%=number%>" /> <%=number%>.
</p>
<%
}
%>
</fieldset>
<p class="buttons">
<button type=submit onclick="javascript: pick();">Continue</button>
</p>
</form>
Javascript/jQuery
function pick(){
var counter = 0;
$("#formulario fieldset p").each(function(index){
var field;
$(this).children("input").each(function() {
if($this.is(':checked')){
field = $(this).val();
}
});
index = index + 1;
texto = "<input type=hidden name=phone_"+index+" value="+field+" />";
$("#formulario").append(texto);
counter = index;
});
cant = "<input type=hidden name=amount id=amount value="+counter+" />";
$("#formulario").append(cant);
}
2.jsp (here I only try to know if I have the info)
<%
int amount = Integer.valueOf(request.getParameter("amount"));
System.out.println(amount);
for(int i = 1; i <= amount; i++){
String s = request.getParameter("phone_"+i);
System.out.println(s);
}
%>
When I try to access to request.getParameter("amount") I get an java.lang.NumberFormatException: null so I think my Javascript/jQuery is wrong.
How can I solve this?.

Are you familiar with debugging web application in a client-side way?
Can you please insert console.log("$("#formulario")) and then a breakpoint after $("#formulario").append(cant);, to see how the form's content changed, and if the hidden input was added ?

use int[] amount= Integer.ValueOf(request.getParameterValues("amount")); instead of request.getParameter("amount");

Well, I finally found the solution and I didn't need any Javascript. Searching in the API I found a method of the request called getParameterNames() that returns an Enumeration of String objects containing the names of the parameters contained in this request.
And I understood that when you submit the form, the checkbox value will be sent if the control is checked. Otherwise, nothing will be sent. So with this information and the method, I changed the way the checkboxes were constructed and use the enumeration to get the values.
BEFORE
<input name=check id="t_<%=number%>" type=checkbox value="<%=number%>" /> <%=number%>.
NOW
<input name="<%=number%>" type=checkbox /> <%=number%>.
So in my second .jsp I get a Enumeration with the names of the selected checkboxes, which are the phone numbers.
java.util.Enumeration enu = request.getParameterNames();
java.util.List<String> numbers = new java.util.ArrayList<String>();
while(enu.hasMoreElements()){
String s = (String)(enu.nextElement());
System.out.println(s);
numbers.add(s);
}

Related

Passing item value from model to JS - MVC C#

Im working on a project with MVC and i'd like to know if there's a way to store the id of an input, which is a value received from one of my model items, into one of my JS variables
here's how the id of the input is being adressed
#foreach (var item in Model) {
<input type="hidden" value="#item.id" id="#item.id">
<input type="hidden" value="#item.nome" id="#item.nome">
<input type="hidden" value="#item.preco" id="#item.preco">
}
and here's what i been trying to do in my .JS file
var id = document.getElementById('#item.id').value;
var nome = document.getElementById('#item.nome').value;
var preco = document.getElementById('#item.price').value;
You can use css class to mark elements where you want to store the id
select all elements with that css class using js
read id attribute for each element using loop
store it the way you need, eg. an array
Well, if you try this you see that your values are saved.
let id = document.getElementById('Id').value;
let name = document.getElementById('Name').value;
let price = document.getElementById('Price').value;
console.log(id);
console.log(name);
console.log(price);
but i somehow fail to use them in html. This doesn't work for example.
<script>
document.getElementById('Id').innerHTML = id;
document.getElementById('Name').innerHTML = name;
document.getElementById('Price').innerHTML = price;
</script>
<h1 id="Id"></h1>
<h1 id="Name"></h1>
<h1 id="Price"></h1>
It's maybe because the input is hidden.
Method 1
Well you can just expose that item ID directly to JavaScript
<script>
// this must be in the .html file, using window makes the variable global
// most rendering frameworks don't do conditional/server side rendering on static js files
window.ITEM_DATA = {
itemId: "#item.id"
}
</script>
<input type="hidden" value="#item.id" id="#item.id">
<input type="hidden" value="#item.nome" id="#item.nome">
<input type="hidden" value="#item.preco" id="#item.preco">
Method 2
Alternatively, you can give each input a class and select all of the classes (or all of the inputs with type hidden)
<input type="hidden" value="#item.id" id="#item.id" class="item-data">
<input type="hidden" value="#item.nome" id="#item.nome" class="item-data">
<input type="hidden" value="#item.preco" id="#item.preco" class="item-data">
// this could be in its own file because we aren't relying on the server
// this is client-side js
const [itemId, itemNome, itemPreco] = document.querySelectorAll(".item-data")
// this could also fit a narrow use case
// document.querySelectorAll("input[type='hidden']")
Edit: added clarification to method 2
you can access model directly in razor page like #ModelName.objectname but you should import model like
#model ModelName
example : #Model.id

Sending Checkbox and Text Input Values to URL String with Javascript

I have a list of products, each individual product has a checkbox value with the products id e.g. "321". When the products checkbox is checked (can be more than 1 selected) i require the value to be collected. Each product will also have a input text field for defining the Qty e.g "23" and i also require this Qty value to be collected. The Qty text input should only be collected if the checkbox is checked and the qty text value is greater than 1. The plan is to collect all these objects, put them in to a loop and finally turn them in to a string where i can then display the results.
So far i have managed to collect the checkbox values and put these into a string but i'm not sure how to collect the additional text Qty input values without breaking it. My understanding is that document.getElementsByTagName('input') is capable of collecting both input types as its basically looking for input tags, so i just need to work out how to collect and loop through both the checkboxes and the text inputs.
It was suggested that i use 2 if statements to accomplish this but i'm new to learning javascript so i'm not entirely sure how to go about it. I did try adding the if statement directly below the first (like you would in php) but this just seemed to break it completely so i assume that is wrong.
Here is my working code so far that collects the checkbox values and puts them in a string. If you select the checkbox and press the button the values are returned as a string. Please note nothing is currently appended to qty= because i dont know how to collect and loop the text input (this is what i need help with).
How can i collect the additional qty input value and append this number to qty=
// function will loop through all input tags and create
// url string from checked checkboxes
function checkbox_test() {
var counter = 0, // counter for checked checkboxes
i = 0, // loop variable
url = '/urlcheckout/add?product=', // final url string
// get a collection of objects with the specified 'input' TAGNAME
input_obj = document.getElementsByTagName('input');
// loop through all collected objects
for (i = 0; i < input_obj.length; i++) {
// if input object is checkbox and checkbox is checked then ...
if (input_obj[i].type === 'checkbox' && input_obj[i].checked) {
// ... increase counter and concatenate checkbox value to the url string
counter++;
url = url + input_obj[i].value + '&qty=' + '|';
}
}
// display url string or message if there is no checked checkboxes
if (counter > 0) {
// remove first "&" from the generated url string
url = url.substr(1);
// display final url string
alert(url);
}
else {
alert('There is no checked checkbox');
}
}
<ul>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="311">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="1" class="input-text qty"/>
</div>
</form>
</li>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="321">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="10" class="input-text qty"/>
</div>
</form>
</li>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="98">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="5" class="input-text qty"/>
</div>
</form>
</li>
</ul>
<button type="button" onclick="javascript:checkbox_test()">Add selected to cart</button>
My answer has two parts: Part 1 is a fairly direct answer to your question, and Part 2 is a recommendation for a better way to do this that's maybe more robust and reliable.
Part 1 - Fairly Direct Answer
Instead of a second if to check for the text inputs, you can use a switch, like so:
var boxWasChecked = false;
// loop through all collected objects
for (i = 0; i < input_obj.length; i++) {
// if input object is checkbox and checkbox is checked then ...
switch(input_obj[i].type) {
case 'checkbox':
if (input_obj[i].checked) {
// ... increase counter and concatenate checkbox value to the url string
counter++;
boxWasChecked = true;
url = url + input_obj[i].value + ',qty=';
} else {
boxWasChecked = false;
}
break;
case 'text':
if (boxWasChecked) {
url = url + input_obj[i].value + '|';
boxWasChecked = false;
}
break;
}
}
Here's a fiddle showing it working that way.
Note that I added variable boxWasChecked so you know whether a Qty textbox's corresponding checkbox has been checked.
Also, I wasn't sure exactly how you wanted the final query string formatted, so I set it up as one parameter named product whose value is a pipe- and comma-separated string that you can parse to extract the values. So the url will look like this:
urlcheckout/add?product=321,qty=10|98,qty=5
That seemed better than having a bunch of parameters with the same names, although you can tweak the string building code as you see fit, obviously.
Part 2 - Recommendation for Better Way
All of that isn't a great way to do this, though, as it's highly dependent on the element positions in the DOM, so adding elements or moving them around could break things. A more robust way would be to establish a definitive link between each checkbox and its corresponding Qty textbox--for example, adding an attribute like data-product-id to each Qty textbox and setting its value to the corresponding checkbox's value.
Here's a fiddle showing that more robust way.
You'll see in there that I used getElementsByName() rather than getElementsByTagName(), using the name attributes that you had already included on the inputs:
checkboxes = document.getElementsByName('checked-product'),
qtyBoxes = document.getElementsByName('qty'),
First, I gather the checkboxes and use an object to keep track of which ones have been checked:
var checkedBoxes = {};
// loop through the checkboxes and find the checked ones
for (i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
counter++;
checkedBoxes[checkboxes[i].value] = 1; // update later w/ real qty
}
}
Then I gather the Qty textboxes and, using the value of each one's data-product-id attribute (which I had to add to the markup), determine if its checkbox is checked:
// now get the entered Qtys for each checked box
for (i = 0; i < qtyBoxes.length; i++) {
pid = qtyBoxes[i].getAttribute('data-product-id');
if (checkedBoxes.hasOwnProperty(pid)) {
checkedBoxes[pid] = qtyBoxes[i].value;
}
}
Finally, I build the url using the checkedBoxes object:
// now build our url
Object.keys(checkedBoxes).forEach(function(k) {
url += [
k,
',qty=',
checkedBoxes[k],
'|'
].join('');
});
(Note that this way does not preserve the order of the items, though, so if your query string needs to list the items in the order in which they're displayed on the page, you'll need to use an array rather than an object.)
There are lots of ways to achieve what you're trying to do. Your original way will work, but hopefully this alternative way gives you an idea of how you might be able to achieve it more cleanly and reliably.
Check the below simplified version.
document.querySelector("#submitOrder").addEventListener('click', function(){
var checkStatus = document.querySelectorAll('#basket li'),
urls = [];
Array.prototype.forEach.call(checkStatus, function(item){
var details = item.childNodes,
urlTemplate = '/urlcheckout/add?product=',
url = urlTemplate += details[0].value + '&qty=' + details[1].value;
urls.push(url)
});
console.log(urls);
})
ul{ margin:0; padding:0}
<ul id="basket">
<li class="products"><input type="checkbox" value = "311" name="item"><input type="text"></li>
<li><input type="checkbox" value = "312" name="item"><input type="text"></li>
<li><input type="checkbox" value = "313" name="item"><input type="text"></li>
</ul>
<button id="submitOrder">Submit</button>

How to get checkbox cheked value in javascript by using html dom

Basically i have a list of checkbox which the data are retrieved from database and i stored it in vector to loop it. Now I need to get the value those are selected(checked) and bring it to another jsp for some purpose, may i know how can i make it ? i get "undefined" value when i alert in javascript. Any help would be appreciated. Thanks
First.jsp
<%
Vector vFruit_code = new Vector();
Vector vFruit_descp = new Vector();
DB_FRUIT.makeConnection();
String SQL = "SELECT * FROM TB_FRUIT WHERE TYPE='FC' WITH UR";
DB_FRUIT.executeQuery(SQL);
while(DB_FRUIT.getNextQuery())
{
String FRUIT_CODE = DB_FRUIT.getColumnString("VALUE1");
String FRUIT_DESCP= DB_FRUIT.getColumnString("VALUE2");
vFruit_code.addElement(FRUIT_CODE);
vFruit_descp.addElement(FRUIT_DESCP);
}
DB_FRUIT.takeDown();
%>
<html>
<head>
<script language="Javascript">
function fnCalulate()
{
document.getPremium.FRUIT_CODE.value = document.mainform.FRUIT_CODE.value;
document.getPremium.submit();
// this part i i get undefined value when i try to alert
alert(document.mainform.FRUIT_CODE.value);
}
</script>
</head>
<body>
<form name="mainform" method="post" action="pop_fruit_route.jsp">
<table>
<tr>
<td>
<%
for (int i=0;i<vFruit_code.size();i++)
{
String sCODE = (String) vFruit_code.elementAt(i);
String sDESCP = (String) vFruit_descp.elementAt(i);
%>
<input name="FRUIT_CODE" type="checkbox" id="<%=sCODE%>" value="<%=sCODE%>" onclick="fnCalulate();"><%= sDESCP %>
<%}%>
</td>
</tr>
</table>
</form>
<form name="getPremium" method="post" action="home/calculation/calFruit.jsp">
<input type="hidden" name="FRUIT_CODE">
</form>
</body>
</html>
i need to get the value from the checkbox which the items are checked to calFruit.jsp
String[] ID = request.getParameterValues("FRUIT_CODE");
output
With what you show, this will fail:
document.getPremium.FRUIT_CODE.value = document.mainform.FRUIT_CODE.value;
because there is no FRUIT_CODE in getPremium.
If you have multiple checkboxes, you can't say document.mainform.FRUIT_CODE.value; FRUIT_CODE will return an array of all your fruit input tags. you can loop over them and get the value for one that is checked, like:
for (var i = 0; i < document.mainform.FRUIT_CODE.length; ++i ) {
if (document.mainform.FRUIT_CODE[i].checked)
document.getPremium.FRUIT_CODE.value = document.mainform.FRUIT_CODE[i].value;
}
alert(document.getPremium.FRUIT_CODE.value);
(though it isn't at all clear to me what you want to happen when multiple ones are checked)
or pass your function the element that was clicked, by changing the call to be:
onclick="fnCalculate(this)"
and the function to:
function fnCalculate(clicked_element) {
document.getPremium.FRUIT_CODE.value = clicked_element.value;
}
though either way you probably want to decide what should happen when a click unchecks a checkbox.
Note that using a library such as jquery makes everything much easier.

How can I prepopulate the remainder of forms based on user input from a first form?

So what I'd like tot do is have a list of forms that show up based on what the user picked in a page before. Now after entering the information in the first form, I would like to give the option of repeating that information for the additional forms . Ex.:
activity 1
Name 1
Name 2
Email
activity 2
Name 1
Name 2
Email
You can see how it can become redundant and tedious if you sign up for many activities. How would I do this in django if possible or javascript if i need to or even html5.
You could do this with just HTML5 and JavaScript (I have no idea what Django is, but this'll be easier if Django is a server-side language that can access form data).
I would make the action attribute of the <form> element in the first webpage lead to the second webpage so that the second webpage would have the GET parameters of that form data, and then in the JavaScript of the second webpage, use those GET parameters to put in data into the form. Here's an example:
tester1.html:
[...]
<form action = "tester2.html">
<input name = "realname" />
<input name = "screenname" />
<input type = "submit" />
</form>
[...]
tester2.html:
[...]
<script>
var form;
window.onload = function() {
var url = document.location.href;
var keys = url.substring(url.indexOf("?")+1, url.length).split("&");
form = document.getElementsByTagName("form")[0];
for (var i = 0; i < keys.length; i++) form[keys[i].substring(0, keys[i].indexOf("="))].value = decodeURIComponent(keys[i].substring(keys[i].indexOf("=")+1, keys[i].length));
};
</script>
[...]
<form>
<input name = "realname" />
<input name = "screenname" />
<input type = "password" name = "password" />
<input type = "submit" />
</form>
[...]

Can I Insert a Javascript Array to my PHP form?

Long story short:
I have a long list of check boxes for adding options to a purchase (TV, Radio, Stove, etc.)
Now I need to insert a LogIn form When they hit next (cut down on the number of quotes created/stored with no customer contact info).
But I was loosing all the options selected and would have to make the customer input again.
So I added an on-click - add to array function for the option id's selected. So that I could collect the ID's before submitting form.
Now the problem... How to send that array to the server with the php form, and I am way to new to Java.
In my research - I can either add the array values to the form action ?optionids=34,891,679,etc
Ugly but O.K.
What I would like is ... If this makes sense.. on-click of next button document.write
My code so far: (in )
<script type="text/javascript">
var numArray = [];
function addToArray(num){
numArray.push(num);
document.getElementById("pTxt").innerHTML = numArray;
return false;
}
</script>
<script>
function jstophp(){
var javavar=document.getElementById("pTxt").value;
document.getElementById("rslt").innerHTML="<?php
$phpvar='"+javavar+"';
echo $phpvar;?>";
}
</script>
I can see the values go in at
<div id="pTxt"></div>
But I can't pull them back out.
Any advice?
You should name your html inputs so that they become an array automatically in the $_POST
<input type="checkbox" name="options[tv]" value="tv">
<input type="checkbox" name="options[radio]" value="radio">
<input type="checkbox" name="options[stove]" value="stove">
Your $_POST will look something like:
options =>
tv => tv,
radio => radio
...
If that is not an option, use a hidden input element rather than a DIV to store your array:
<input type="hidden" id="pTxt" name="idList">
<script>
var numArray = [];
function addToArray(num){
numArray.push(num);
document.getElementById("pTxt").value = numArray;
return false;
}
</script>

Categories

Resources