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

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.

Related

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>

Grails richui autocomplete passing object to function or updating object ID

I've got a table with a load of auto complete boxes in it which look like so...
<richui:autoComplete style="width:500px" name="objSelect[${newRow-1}].id" value= "" action="${createLinkTo('dir': 'object/searchAJAX')}" forceSelection = "true" maxResultsDisplayed="20" minQueryLength ="3" onItemSelect="updateHiddenInput(id,${newRow-1})" />
I've got it to call a function called updateHiddenInput when a user selects a value passing in the id selected as well as the row the autocomplete is on (this function then updates a hidden field in the same row, using the values passed in, with the ID). The function looks like so: -
function updateHiddenInput(id, num){
var objID = "objectID[" + num + "].id";
$(document.getElementById(objID)).val(id);
}
Everything works until I add a new row within my table, this pushes everything down one row and stops the autocomplete from updating the right rows hidden field (as its still referencing the old row).
Currently I have another piece of code that goes through and renames all the fields when a new row is inserted, but I have no idea how to update the autocomplete so that it passes through the right row number, anyone know how I can alter this?
The only other alternative I could think of would be to just pass through the object itself as well as the ID I can then locate the hidden based off the object, but I can't work out how to do this, any suggestions gratefully received! :S
I've tried changing
onItemSelect="updateHiddenInput(id,${newRow-1})"
to
onItemSelect="updateHiddenInput(id,this)"
Theoretically so I can just pass through the autocomplete object and from there just traverse the page to find the hidden field I want to update. However when I then attempt to use that object in my function, for example with something like: -
var mynumber = $(myobject).closest('td').find('input').val();
I always get an "undefined" returned when I try to alert back the value...
If I just put in an alert(myobject) in the function it returns AutoComplete instance0 autoLook[0].id but if I've inserted new lines the id value doesn't change (i.e the objects id is now autoLook[3].id but it still shows [0], which I think could be part of the problem but I've got now idea how I can update this value...
I notice when looking in firebug at the html there is a /script linked to the autocomplete which could be the problem as this doesn't get updated when new lines are added and I can see multiple references to the old/original id value (see below) so maybe the passing through of this isn't passing the current objects values through...?
<script type="text/javascript">
var autoCompleteDataSource = new YAHOO.util.XHRDataSource("/Framework/object/searchAJAX");
autoCompleteDataSource.responseType = YAHOO.util.XHRDataSource.TYPE_XML;
autoCompleteDataSource.responseSchema = {
resultNode : "result",
fields : [
{ key: "name" },
{ key: "id" }
]
};
;
autoComplete = new YAHOO.widget.AutoComplete('autoLook[0].id','ad186a42e45d14d5cde8281514f877e42', autoCompleteDataSource);
autoComplete.queryDelay = 0;
autoComplete.prehighlightClassName = 'yui-ac-prehighlight';
autoComplete.useShadow = false;
autoComplete.minQueryLength = 3;
autoComplete.typeAhead = false;
autoComplete.forceSelection = true;
autoComplete.maxResultsDisplayed = 20;
autoComplete.shadow = false;
var itemSelectHandler = function(sType, args) {
var autoCompleteInstance = args[0];
var selectedItem = args[1];
var data = args[2];
var id = data[1];
updateHiddenInput(id,this) };
autoComplete.itemSelectEvent.subscribe(itemSelectHandler);
</script>
My thanks so far to user1690588 for all his help thus far! :)
On further digging I'm convinced that my issues is down to the line autoComplete = new YAHOO.widget.AutoComplete('autoLook[0].id','a5b57b386a2d1c283068b796834050186', autoCompleteDataSource); specifically the part where its inputting autoLook[].id and if I could change this I'd then be ok, but this line is auto generated and I've got no idea how to update it, anyone have any similar experience?
I have not much idea about your gsp page but I tried it on my side:
My gsp:
<!DOCTYPE html>
<html>
<head>
<resource:autoComplete skin="default"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var counter = ${list.size()};
function asd() {
jQuery.ajax({
url: " ${createLink(controller: 'oauthCallBack', action: 'testAuto')}",
data: "idx=" + counter++,
success: function (data) {
jQuery("#tableId").append("<tr><td>" + data + "</td></tr>");
}
});
}
function updateHiddenInput(id, tg) {
jQuery(tg).val(id);
}
</script>
</head>
<body>
<g:form>
<table id="tableId">
<g:each in="${list}" var="vr" status="idx">
<tr>
<td>
<richui:autoComplete name="name" id="uniqueId${idx}" action="${createLinkTo('dir': 'oauthCallBack/test')}" onItemSelect="updateHiddenInput(id, someId${idx})"/>
<g:hiddenField name="someName" id="someId${idx}" value=""/>
</td>
</tr>
</g:each>
</table>
</g:form>
<button onclick="asd()">Add</button>
</body>
</html>
My action:
def testAuto() {
render template: 'addNew', model: [idx: params.idx]
}
My template(addNew):
<richui:autoComplete name="name" id="uniqueId${idx}" action="${createLinkTo('dir': 'oauthCallBack/test')}"
onItemSelect="updateHiddenInput(id, someId${idx})"/>
<g:hiddenField name="someName" id="someId${idx}" value=""/>
Try this..,.
EDIT.....................................................................................
I supposed that you have successfully updated all the input field names. Then you can edit hidden field like:
View:
<tr class="dummyClass">
<td>
<richui:autoComplete name="name[${idx}]" id="uniqueId[${idx}]" action="${createLinkTo('dir': 'oauthCallBack/test')}" onItemSelect="updateHiddenInput(id, this)"/>
<g:hiddenField name="someName[${idx}]" id="someId[${idx}]" value=""/>
</td>
</tr>
jQuery:
function updateHiddenInput(id, tg) {
jQuery(tg._elTextbox).closest("tr.dummyClass").find("input[type=hidden]").val(id);
}
EDIT.....................................................................................
Why you need to change the 'id'? Changing name is sufficient to send values in order. And you can update the hidden field without id as above edit.
If you still need to change the id then you can change it by cloning the tr and then use regex. See this answer for full working example.

Pass some checkbox values from one JSP to another

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

How to return a variable from a javascript function into html body

I am still new to javascript, and I am trying to get a function to return a variable using html & javascript. Basically the function should just return whichever radio button that the user clicks on, although at the moment I don't see anything being returned at all.
The function is here:
<script type="text/javascript">
function GetSelectedItem() {
var chosen = ""
len = document.f1.r1.length
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
chosen = document.f1.r1[i].value
}
}
}
return chosen
</script>
And then in the html section I have these radio buttons, and my attempt to get the variable "chosen" output to the screen.
<form name = f1><Input type = radio Name = r1 Value = "ON" onClick=GetSelectedItem()>On
<Input type = radio Name = r1 Value = "OFF" onClick =GetSelectedItem()>Off</form>
<script type ="text/javascript">document.write(chosen)</script>
At the moment nothing seems to be getting returned from the function (although if I output the variable 'chosen' inside the function then it is working correctly.
Thanks in advance!
Here's a little simpler approach.
First, make a few corrections to your HTML, and create a container to display the output:
<form name = "f1"> <!-- the "this" in GetSelectedItem(this) is the input -->
<input type = "radio" Name = "r1" Value = "ON" onClick="GetSelectedItem(this)">On
<input type = "radio" Name = "r1" Value = "OFF" onClick ="GetSelectedItem(this)">Off
</form>
<div id="output"></div>
Then change your script to this:
<script type="text/javascript">
// Grab the output eleent
var output = document.getElementById('output');
// "el" is the parameter that references the "this" argument that was passed
function GetSelectedItem(el) {
output.innerHTML = el.value; // set its content to the value of the "el"
}
</script>
...and place it just inside the closing </body> tag.
Click here to test a working example. (jsFiddle)
document.write takes a string, and outputs it as part of the HTML. This is not a live value that updates when the variable pointing at the string is updated.
For that, you will need to perform DOM manipulation.
Change your JavaScript function to something like that:
<script type="text/javascript">
function GetSelectedItem() {
len = document.f1.r1.length;
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
document.getElementById('test').textContent = document.f1.r1[i].value;
}
}
}
</script>
And then in the body:
<div id="test"></div>
As I put in the post. Using JQuery would make your life easy for this kind of task (and many others for the matter). The really nice thing about JQuery is that it often makes your JavaScript syntax much easier then you can learn the nitty gritty details of javascript as you go.
First, add the following script tag into your html page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
Now you have the JQuery API
Then you could rewrite the function like this.
function GetSelectedItem(btnRadio)
{
var jqElem = $(btnRadio);
$('#output').html(jqElem.attr('value')); //attr('<name of attributre'>) gets the value of the selected attribute
}
Your html would look like this
<form name = "f1">
<input type = "radio" name = "r1" value = "On" onclick="GetSelectedItem(this)">On
<input type = "radio" name = "r1" value = "Off" onclick ="GetSelectedItem(this)">Off
</form>
<div id="output">
</div>
More or less, the .html() can both get and set the html of the selected element. So we are just simply inserting the value into the div tag.

Expanding HTML forms using Javascript

I have a simple HTML form that asks a user to input their name, SKU, quantity, and comments. This is for a simple inventory request system.
<html>
<body>
<form id="myForm" method="post">
<input type="submit">
<br>Name: <input type="text" name="form[name]">
<br>SKU: <input type="text" name="form[SKU1]">
<br>Quantity: <input type="text" name="form[quantity1]">
<br>Comment: <input type="text" name="form[comment1]">
</form>
Add item
<script>
var num = 2; //The first option to be added is number 2
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "form[SKU"+num+"]"; // form[varX]
newOption.type = "text";
theForm.appendChild(newOption); //How can I add a newline here?
optionNumber++;
}
</script>
</body>
</html>
Currently I can only get it working where it will add a single form value. I would like to recreate the entire myForm except for the name field with a single click.
Your post is very old, so presumably you've found an answer by now. However, there are some things amiss with your code.
In the JavaScript code you have
var num = 2;
This is the number that is incremented to keep track of how many "line-items" you will have on the form. In the function addOption(), though, instead of incrementing num you have
optionNumber++;
You never use optionNumber anywhere else. Your code works once, when you add the first item, but since you increment the wrong variable, you are effectively always adding option 2.
Oh, and adding the newline: you need to append a <br> element.

Categories

Resources