JSP giving NullPointerException for request.getParameter() - javascript

I'm new to jsp and am creating a webpage that has a form with a select box and a few other input boxes.
I'm populating these input boxes automatically with values from properties file:
NumConfig.properties
SELECT= , ,
ONE=1,I,FIRST
TWO=2,II,SECOND
THREE=3,III,THIRD
Here is my form:
<html>
<body>
<form name="NumDetail" id="NumDetail" method="post">
<div>
<table>
<tr>
<th rowspan="2">Select
<select id="SelectText" name="SelectText" onchange="this.form.submit()">
<option value="ONE">ONE</option>
<option value="TWO">TWO</option>
<option value="THREE">THREE</option>
</select>
</th>
<th align="center">Number</th>
<th align="center">Roman</th>
<th align="center">Position</th>
</tr>
<tr>
<td align="center">
<input type="text" size=10 id="number">
</td>
<td align="center">
<input type="text" id="roman">
</td>
<td align="center">
<input type="text" id="position">
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
And this is the JS code I'm using to load values from properties file:
< script type = "text/javascript" >
<%
ResourceBundle resource = ResourceBundle.getBundle("NumConfig");
String dbname;
if (request.getParameter("SelectText") == null)
dbname = "SELECT";
dbname = request.getParameter("SelectText");
String[] num = resource.getString(dbname).split(","); %>
var number = "<%= num[0]%>";
var rom = "<%= num[1]%>";
var pos = "<%= num[2]%>";
document.getElementById("number").value = number;
document.getElementById("roman").value = rom;
document.getElementById("position").value = pos; < /script>
I can indirectly open this page by appending ?SelectText value in the URL.
But when opening this page directly I get NullPointerException at the line
String[] num = resource.getString(dbname).split(",");
Two Questions:
How do I perform a null check or give the request parameter a default value so that page does not error out?
Once I select a value from the dropdown and the form submits, the select box does not retain its value and goes back to the default. How to resolve this?

You just need an else statement
if (request.getParameter("SelectText") == null)
dbname = "SELECT";
else
dbname = request.getParameter("SelectText");
To make an option selected by default, you should try this selected="selected". Stock the value somewhere and change your selected option dynamically.
<option value="ONE" selected="selected">ONE</option>

Firstly my recommendation would be not to mix Java code within HTML code in a JSP page. Try using a Java Servlet to manage your request and respose so you don't end up having a messy code.
I'll answer your questions below:
You are checking whether the parameter "SelectText" is null, and if that's the case then giving to 'dbname' a default value but the next instruction is replacing this given value with null.
The code should look like this:
String dbname = "SELECT";
String requestValue = request.getParameter("SelectText");
if (requestValue != null) {
dbname = requestValue;
}
Have you tried replacing your form request method with GET instead of POST?

Related

replace input type select multiple by some kind of list to force selected elements

I'm trying to achieve something like on this screenshot :
screen
it's basically a form in PHP/Html, and working nicely.
however it's not exactly what I want to do.
I want to take elements from the left and put them to the right side, and get the form validated with the right side elements.
atm, everything works nicely, but my problem is : all elements on the right side need to be "selected" before submitting the form.
is there a way of doing this without having the elements on the right side being "selected".
technically, I just want the "pushed elements" to the right side to be all selected by default in the form.
I suppose my problem comes from the fact that I'm using select instead of another kind of input (can I use a textarea, or some kind of other input ?)
thanks
FYI, here is my source code for this
javascript
<script type="text/javascript" language="Javascript">
function move(sens) {
var i, sourceSel, targetSel;
if (sens == 'right') {
sourceSel = document.getElementById('selectBoxOne');
targetSel = document.getElementById('selectBoxSecond');
} else {
sourceSel = document.getElementById('selectBoxSecond');
targetSel = document.getElementById('selectBoxOne');
}
i = sourceSel.options.length;
while (i--) {
if (sourceSel.options[i].selected) {
targetSel.appendChild(sourceSel.options[i]);
}
}
}
</script>
php/html
<tr>
<th>Associated rights</th>
<td>
<table border="0" cellspacing="0" id="table">
<tr>
<td>
Available (unused) rights (pbroles) <br />
<select name="kiki" multiple="multiple" id="selectBoxOne" size="10" style="width: 325px">
<?php
$q_pbroles = '
SELECT
p.name
FROM
firecall_pbroles p
WHERE
p.name not in (
SELECT
p.name
FROM
firecall_pbroles p,
firecall_roles r,
firecall_l_roles l,
firecall_pbroles_types t
WHERE
p.id = l.pbrole_id
AND
r.id = l.role_id
AND
t.id = p.type
AND
r.id = '.$role_id.'
)
;';
$prep = $dbh->prepare($q_pbroles);
$prep->execute();
$arrAll = $prep->fetchAll();
foreach($arrAll as $data)
{
echo '<option id="multiple'.$data['id'].'" value="'.$data['id'].'">'.$data['name'].'</option>';
}
?>
</select>
<br />
Ctrl+Click to select multiple pbroles
</td>
<td>
<input type="button" value="<<" onclick="move('left');"><br />
<input type="button" value=">>" onclick="move('right');">
</td>
<td>
pbroles in this Role<br />
<select name="pbRoles[]" multiple="multiple" id="selectBoxSecond" size="10" style="width: 325px">
<?php
$q_pbroles = '
SELECT
p.id,
p.name,
t.roletype,
t.descr
FROM
firecall_pbroles p,
firecall_roles r,
firecall_l_roles l,
firecall_pbroles_types t
WHERE
p.id = l.pbrole_id
AND
r.id = l.role_id
AND
t.id = p.type
AND
r.id = '.$role_id.'
ORDER BY
p.type;
';
$prep = $dbh->prepare($q_pbroles);
$prep->execute();
$arrAll = $prep->fetchAll();
foreach($arrAll as $data)
{
echo '<option id="multiple'.$data['id'].'" value="'.$data['id'].'" selected>'.$data['name'].'</option>';
}
?>
</select>
<br />
Ctrl+Click to select multiple pbroles
</td>
</tr>
</table>
</td>
</tr>
There are several ways to achieve this.
See Paul Dixon's answer on "how to pass array through hidden field"
You can add an event listener to the form submit event and then add each selectBoxSecond option to a hidden field inside your form like this:
var form = document.getElementsByTagName('form')[0];
form.onsubmit = function(e) {
var elements = document.getElementsByClassName('hidden_pbRoles');
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
var sourceSel = document.getElementById('selectBoxSecond');
i = sourceSel.options.length;
while (i--) {
var input_hidden = document.createElement("input");
input_hidden.setAttribute('name', 'pbRoles[]');
input_hidden.setAttribute('type', 'hidden');
input_hidden.setAttribute('value', sourceSel.options[i].text);
form.appendChild(input_hidden);
}
};
Now you can also remove name and multiple="multiple" from the second select selectBoxOne:
<select id="selectBoxSecond" size="10" style="width: 325px">
</select>
You can check my working example here: http://zikro.gr/dbg/html/listpost.php
Just move some options from the left to the right select box and then hit submit button to see the POST data result after the page refresh.

Javascript not enabling html forms

It has been ages i don't work anything in JS, i'm trying to do with a select enable another html form when certain selected option is being chosen. this is my script:
<script>
function Activar() {
var e = document.getElementById('perm_tipo');
var strUser = e.options[e.selectedIndex].text;
if(strUser=="familiar"){
document.getElementById('paciente').disabled = false;
}else{
document.getElementById('paciente').disabled = true;
}
}
i have those html select inside a form, i think that could be the problem but checking on google seems that's should'nt be an issue.
here is my html code:
<form id="registro" action="admin_panel.php" method="post">
<table border="0">
<tr>
<td>Tipo de permiso</td>
<td>
<select name="perm_tipo" onchange="Activar()">
<?php
permiso();
?>
</select>
<br>
</td>
<td>Paciente</td>
<td>
<select id="paciente" disabled>
<?php
pacientes();
?>
</select>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Registrar usuario"/><br>
</td>
</tr>
</table>
the php functions just fill the select options with data from some database, no big deal there, they work, no problem there.
Since you are using getElementById, you should use 'id' instead of 'name' in the 'select' element.
<select id="perm_tipo" onchange="Activar()">
....
</select>
More refactor: you can pass the DOM element itself in the event listener and you don't have to do var e = document.getElementById('perm_tipo'); in the first place
<select name="perm_tipo" onchange="Activar(this)">
....
</select>
<script>
function Activar(e) {
var strUser = e.options[e.selectedIndex].text;
if(strUser=="familiar")
document.getElementById('paciente').disabled = false;
else
document.getElementById('paciente').disabled = true;
}
</script>

How to get select box to show all its contents when checking from python script.

I want to have two select boxes, one empty and one populated. The user will move some of the items from the populated select box to the empty select box. I have that working. What I need help on is that when the items are moved over to the empty select box and submit is pressed, no data is sent concerning the empty select box that is now populated. I have found that this is because as the person moves items over they are not kept selected. Is there something besides a select box that looks like a select box that I can use or is there some other way for me to find out what has been moved from one box to the other?
I am doing the processing of the form in python and have attached the basic code that I am using.
.html:
<html>
<head>
</head>
<script language="Javascript">
function SelectMoveRows(SS1,SS2)
{
var SelID='';
var SelText='';
// Move rows from SS1 to SS2 from bottom to top
for (i=SS1.options.length - 1; i>=0; i--)
{
if (SS1.options[i].selected == true)
{
SelID=SS1.options[i].value;
SelText=SS1.options[i].text;
var newRow = new Option(SelText,SelID);
SS2.options[SS2.length]=newRow;
SS1.options[i]=null;
}
}
SelectSort(SS2);
}
function SelectSort(SelList)
{
var ID='';
var Text='';
for (x=0; x < SelList.length - 1; x++)
{
for (y=x + 1; y < SelList.length; y++)
{
if (SelList[x].text > SelList[y].text)
{
// Swap rows
ID=SelList[x].value;
Text=SelList[x].text;
SelList[x].value=SelList[y].value;
SelList[x].text=SelList[y].text;
SelList[y].value=ID;
SelList[y].text=Text;
}
}
}
}
</script>
<body>
<form name="projectBuild" action="../cgi-bin/pythonTest.cgi" enctype="multipart/form-data" method="POST">
<table>
<tr>
<td align="center">
<SELECT NAME="selectList" style="width: 100%" MULTIPLE>
<!--<SELECT NAME="selectList" MULTIPLE>-->
<OPTION VALUE="crc">CRC</option>
<OPTION VALUE="vector">Vector</option>
<OPTION VALUE="mm">Matrix Multiply</option>
<OPTION VALUE="bubblesort">Bubble Sort</option>
<OPTION VALUE="quicksort">Quick Sort</option>
</SELECT>
</td>
<td align="center" >
<input type="button" name="add" value="Add >>" onClick="SelectMoveRows(document.projectBuild.selectList,document.projectBuild.userSelections)">
<br>
<input type="button" name="remove" value="<< Remove" onClick="SelectMoveRows(document.projectBuild.userSelections,document.projectBuild.selectList)">
</td>
<td allign="center">
<SELECT NAME="userSelections" style="width: 100%" MULTIPLE>
<!--<SELECT NAME="userSelections" MULTIPLE>-->
<!-- <OPTION VALUE="placeholder">placeholder</option> -->
</SELECT>
</td>
</tr>
<tr>
<td>
</td>
<td align="center">
<input type="submit" value="Submit">
</td>
</table>
</body>
</html>
.cgi:
#!/usr/bin/python
import cgi, os, sys, commands
myForm = cgi.FieldStorage()
pickedAcc = myForm.getvalue("userSelections")
leftAcc = myForm.getvalue("selectList")
print pickedAcc
print "Left Accelorator list: "
print leftAcc
Before submitting the form, loop through all the options in the userSelections select and set the selected attribute of each option to true. Modify your form as follows
<form name="projectBuild"
onSubmit="selectAll(document.projectBuild.userSelections)"
action="../cgi-bin/pythonTest.cgi"
enctype="multipart/form-data"
method="POST">
In the selectAll method, you loop through all the options and set the selected attribute to true.
Execute a JavaScript when a form is submitted
Javascript loop through ALL HTML select (See the 2nd answer)

With bind/on change how to show a Row

I have a form using coldfusion that currently is using binding to generate a value. After a user selects from a pull down a selection is automatically generates a value 'Y' or 'N' generated from a table. What I need to do is use that value, in this case if value is 'Y' to display more questions to be answered. Here is what the current coding looks like.
<td>Select Category:
<cfselect name="catdesc"
title="Select category to generate related services"
bind="cfc:servicetype2.cat_description()"
bindonload="true"/><br />
</td>
</tr>
<tr id="serv_ty2" style="display: inline;">
<td></td>
<td>Select Service:
<cfselect name="service_type"
bind="cfc:servicetype2.getServiceType2({catdesc})"
bindonload="false"/></td>
</tr>
<tr id="lr_verify" style="display: inline;">
<td></td>
<td>Labor Relations Required:
<cfinput name="lr_needed" <!---
onchange="document.getElementById('lr_question').style.display = (this.selectedIndex == Y) ? 'inline' : 'none'"--->
bind="cfc:servicetype2.getLR({service_type})"
onchange="editLR()"
bindonload="false"/></td>
</tr>
Here is the additional questions I want to show if Y is generated
<TR id="lr_question" name="lr_question" style="display: none;">
<td align="left" nowrap>nbsp;<b>Additional Question:</b><br>(Hold Ctrl to select multiple)</td>
<td align="left">Question:<br><br>
<select id="lr_quest" name="lr_quest" multiple="multiple" required="NO" size="5">
<option name="abc" id="abc">
Choice 1</option>
<option name="abc2" id="abc2">
Choice 2</option>
</select>
From my research I tried two solutions but neither work I am assuming I have the incorrect syntax or my thinking is correct.
Here is what the attempt java function was:
function editLR()
{
// if 'Y' then additional questions for service type should show
var lrshow = document.getElementById("lr_needed");
if( lrshow == 'Y' ) {
lr_question.style.display = "inline";
}
else if ( lrshow == 'N' ) {
lr_question.style.display = "none";
}
else if ( lrshow == '' ) {
lr_question.style.display = "none";
}
}
Let me know if you have any suggestion I apologize if I did not explain myself correctly. Thanks in advance for any assistances I am still new to javascript and coldfusion so learning all the elements that are available still.
To start, you have this:
var lrshow = document.getElementById("lr_needed");
Add this line after it and see what you get.
alert("lrshow is " + lrshow);
Then see if this makes any difference:
var lrshow = document.getElementById("lr_needed").value;
alert("lrshow is " + lrshow);

Jquery: Enable/Disable based on value of dropdown is not working for dynamically generated inputs

I have a form where I can add new rows to increase the form elements using jquery. In that form I have two dropdown options (Name:type and accounts) and two text inputs (Name:debit_amount and credit_amount).
Problem:
I have developed a jquery code to enable/disable text inputs based on the selected values from dropdown options. But the code works fine only if I don't add new rows. If I add a new row it only works for the very first row, I mean it disables/enables inputs of the first row only.
For the sake of clarity I have not provided the code for adding new rows below, but to get a live picture of all my codes please check this link, jsfiddle.net
Could you please tell me what change should I bring in my code to be able to make all the inputs (including inputs of generated rows ) disable/enable based on the selected values?
My HTML
<h2>Add Another Input Box</h2>
<table class="dynatable">
<thead>
<tr>
<th>Type</th>
<th>Account Name</th>
<th>Debit</th>
<th>Credit</th>
</tr>
</thead>
<tbody id="p_scents">
<tr>
<td>
<select name="type" id="type">
<option value="Debit">Debit</option>
<option value="Credit">Credit</option>
</select>
</td>
<td>
<select name="accounts" id="accounts">
<option value="">SELECT</option>
<option value="One">One</option>
<option value="Two">Two</option>
</select>
</td>
<td>
<input type="text" name="debit_amount" id="debit_amount" />
</td>
<td>
<input type="text" name="credit_amount" id="credit_amount"/>
</td>
</tr>
</tbody>
Conditions for disabling/Enabling
1. If type selected == Debit and a value from accounts is selected then enable debit_amount input and disable credit_amount input
2. If type selected == Credit and a value from accounts is selected then enable credit_amount input and disable debit_amount input
3. If any of the values of type and accounts is not selected disable both
My Jquery Code for disabling/enabling inputs based on dropdown value
//ON the change of accounts(dropdown select)
$("#accounts").change(function() {
var type = $("select#type").val();
var accounts = $("select#accounts").val();
if (type == "Debit") {
$('#credit_amount').attr("disabled", true);
$('#debit_amount').removeAttr("disabled", true);
}
if (type == "Credit") {
$('#debit_amount').attr("disabled", true);
$('#credit_amount').removeAttr("disabled", true);
}
if (accounts == "") {
$('input[name=credit_amount]').val('');
$('input[name=debit_amount]').val('');
$('#debit_amount').attr("disabled", true);
$('#credit_amount').attr("disabled", true);
}
});
//ON the change of type(dropdown select)
$("#type").change(function() {
var accounts = $("select#accounts").val();
var type = $("select#type").val();
if (type == "Debit" && accounts != '') {
$('input[name=credit_amount]').val('');
$('#credit_amount').attr("disabled", true);
$('#debit_amount').removeAttr("disabled", true);
}
if (type == "Credit" && accounts != '') {
$('input[name=debit_amount]').val('');
$('#debit_amount').attr("disabled", true);
$('#credit_amount').removeAttr("disabled", true);
}
});
The problem is that your input elements all have the same id attribute values, ie: "debit_amount" and "credit_amount", so jQuery doesn't know which ones the "#debit_amount" and "#credit_amount" selectors refer to.
Element ids should be unique in the page, so you should append a sequence number to the end of each eg:
<select name="accounts_1" id="accounts_1">
....
<input type="text" name="debit_amount_1" id="debit_amount_1" />
<input type="text" name="credit_amount_1" id="credit_amount_1" />
Two solutions:
use the jQuery traversal API to find the input elements relative to the select element that triggered the onChange event. This is brittle and will break if you change your markup too much
parse the sequence number out of the <select> id attribute and use it to find the <input>s you want to modify

Categories

Resources