Checkbox always returning null in jsp - html

i am building a contact form and have a checkbox that looks like this:
<input type="Checkbox" name="infomaterial" value="test">send info material<br>
i am then using request.getParameter like this:
request.getParameter("infomaterial")
this is working fine with textboxes and textfields, but it is not working with checkboxes.
I always get null, no matter it is checked or not (i expect it being null when not checked?).. The checkbox is in the right position, too. Can someone tell me what i am doing wrong?

Use getParameterValues to get array of selected checkboxes:
Servlet:
String[] infomaterials= request.getParameterValues("infomaterial");
for (String infomaterial:infomaterials) {
System.out.println(infomaterial);
}
Also note, you will only get values for those checkboxes which are selected. If a checkbox is not selected, it's value will not be available in getParameterValues.

Thanks for your answers.
I found the problem. I have an "owasp SecurityWrapper" in my program. Somehow, this blocks everything except textfields and textboxes. If i turn it off, it works like expected. Still have to find out why it blocks those Checkboxes..

<input type="Checkbox" class="msgChk" name="infomaterial" value="test">send info material<br>
var checked = null;
var input = document.getElementsByClassName('msgChk');
for(var i=0; inputElements[i]; ++i) {
if(inputElements[i].checked) {
checked = inputElements[i].value;
break;
}
}

This is an old post, but please try
boolean infomaterialIsChecked= Boolean.parseBoolean( request.getParameter("infomaterial") );
or
boolean infomaterialIsChecked= request.getParameter("infomaterial") != null;
The Second Option is better. It worked for me

Related

Select checkbox from array values in AngularJS

I have created a page which contains some text boxes, radio buttons and check boxes. I am using this page to save new data or edit the existing one. I am able to save new data but for editing the data, the page should show some predefined values that it is getting from a variable. I am able to get and set the values for text boxes and radio buttons from that variable. But I am not able to check the check boxes. I have plenty of check boxes so I am using ng-repeat for the values to be displayed on page. I am setting the values of selected check boxes to an array and passing that value to my service layer.
Below are my code snippets:
HTML:
<div id="activityCheckboxList" class="checkboxList">
<div ng-repeat="activity in activities">
<label>
<input type="checkbox" ng-true-value="activity" ng-checked="selection.indexOf(activity) > -1" ng-click="toggleSelection(activity)"/>
<span>{{activity.activityName}}</span>
</label>
</div>
</div>
app.js:
$scope.selection=[];
$scope.getActivities(); //this sets values in $scope.activities which is a list coming from service layer
//Get Selected Activities from Check Boxes
$scope.toggleSelection = function toggleSelection(activity){
var idx = $scope.selection.indexOf(activity);
if(idx > -1){
$scope.selection.splice(idx, 1);
}
else{
$scope.selection.push(activity);
}
};
After this, while clicking on submit, I am passing $scope.selection which will contain my activity objects.
For editing the data, I can put the data in selection[]. But how to check the check boxes using that and after that user should be uncheck/check them again. I tried using foreach loop but it didn't help.
Thanks in advance
As "activity" is an object, indexOf is not right way to find the index. I have made few changes to your code
html
<input type="checkbox" ng-true-value="activity"
ng-checked="checkInSelectionList(activity)" ng-click="toggleSelection(activity)"/>
<span>{{activity.activityName}}</span>
js
$scope.checkInSelectionList = function (item) {
for(var i=0; i<$scope.selection.length;i++){
if($scope.selection[i]['ID'] == item['ID']){
return true;
}
}
}
You can also use underscore to find the index of an object.
https://jsfiddle.net/nors536b/

enter term into hidden form field with html and css possible?

I have created a form in HTML/CSS on my website.
Now, my idea is to give out links that would contain some string (basically like an affiliate link) and would like that string to be entered in a hidden form field to be submitted, or somehow else, have that string in the submitted data.
is there an easy way to do this?
There are two ways of approaching this, both of which use a GET variable in the link you distribute.
First off, let's assume that--for example's purpose--your special string is abc123. You would then distribute a link that follows the form http://example.com/my/form/?affiliate=abc123.
Assuming that, here are two solutions, one in PHP and another in Javascript.
PHP Solution
This one is fairly easy, as long as you're just setting a hidden field.
<input type='hidden' name='affiliate' value='<?= htmlspecialchars($_GET['affiliate'], ENT_QUOTES, 'UTF-8'); ?>' />
Update: Added htmlspecialchars() call to escape any input, to prevent security issues with users setting the GET variable manually.
Javascript Solution
HTML
<input type='hidden' id='affiliate-input' name='affiliate' />
Javascript
This solution relies on jQuery. If you want a pure JS solution, let me know.
var $_GET = {};
// When the page loads, set the input value
$(document).ready(function(){
setupGetVariables();
var affiliateId = $_GET["affiliate"];
$("#affiliate-input").val(affiliateId);
});
function setupGetVariables()
{
if(document.location.toString().indexOf('?') !== -1) {
var query = document.location
.toString()
// get the query string
.replace(/^.*?\?/, '')
// and remove any existing hash string (thanks, #vrijdenker)
.replace(/#.*$/, '')
.split('&');
for(var i=0, l=query.length; i<l; i++) {
var aux = decodeURIComponent(query[i]).split('=');
$_GET[aux[0]] = aux[1];
}
}
}
The setupGetVariables() method was helped by this answer.

checkbox value is not sent in HTTPRequest if unchecked

There is a checkbox in my jsp page
<input type="checkbox" name="myCheck" id="myCheck">
I am submitting the form and on server side,I am trying to retrieve it
using
request.getParameter("myCheck");
If I have checked the checkbox,it is coming in request as true else it is not present in request object.
My Requirement is that It should also come as false if I have not checked it.
Any suggestion?
UPDATE
I am using GET method and yes it is present in the form which I am submitting.
From accepted answer in stackoverflow
How you can know if its checked
Clarification..
For example:
<input type="hidden" name="checkboxNamesList" value="nameCheckbox1" />
<input type="hidden" name="checkboxNamesList" value="nameCheckbox2" />
<input type="hidden" name="checkboxNamesList" value="nameCheckbox3" />
<input type="hidden" name="checkboxNamesList" value="nameCheckbox4" />
Then, you can get checkboxNamesList from the request (it will be a String[]) so you will have all the checkboxes params names. If you get a parameter for one of the checkboxes name and value is null, it means that checkboxe was not checked
Well, as unchecked checkboxes are not present in the request you don't know whose checkboxes in the JSP were not checked but you need to know it in order to write in your data file something like checkbox_name1=unchecked.
So, how to do that? First, you need to know what checkboxes (uncheck or not) were present in the request. For that, you can use the code below and get name of all checkboxes present in the JSP:
String[] checkboxNamesList= request.getParameterValues("checkboxNamesList");
Then, let look for unchecked checboxes:
for (int i = 0; i < checkboxNamesList.length; i++) {
String myCheckBoxValue = request.getParameterValues(checkboxNamesList[i]);
// if null, it means checkbox is not in request, so unchecked
if (myCheckBoxValue == null)
writer.append(checkboxNamesList[i] + "=unchecked");
// if is there, it means checkbox checked
else
writer.append(checkboxNamesList[i] + "=checked");
}
I cannot understand why the value is not in the request object. I think one possible mistake is the missing value attribute.
To your second question:
In your backend you have to define a default value first and then check to null:
public boolean myCheckBox = false;
if (request.getParameter("myCheck") != null) {myCheckBox = true}

How to make two checkboxes required out of three in HTML?

<input type="checkbox" name="Package1" value="packagename">
<input type="checkbox" name="Package2" value="packagename">
<input type="checkbox" name="Package3" value="packagename">
How to make any two checkboxes required for the user to submit the form. The user should not be able to submit the form unless he has checked atleast two checkboxes?
How to achieve that?
Rename checkboxes to name=package[] and values 1, 2, 3.
Then in PHP you'll have o condition (if you send form with GET method, just change POST to GET):
if (isset($_POST['package']) && count($_POST['package']) >= 2) {/* continue */}
If you want to validate it in browser (JS), than:
<script>
var i = 0;
$('[type="checkbox"]').each(function() {
if ($(this).is(':checked')) {
i++;
}
});
if (i <= 1) {
return false; // disable sending form when you've checked 1 checkbox in maximum
}
</script>
Add a class that refers only these checkboxes and then count how many are checked.
A quick and dirty way to validate the checkboxes using JavaScript:
JavaScript
checkCheckboxes = function() {
var numberOfCheckedCheckboxes = 0;
var checkbox1 = document.getElementsByName("Package1")[0];
var checkbox2 = document.getElementsByName("Package2")[0];
var checkbox3 = document.getElementsByName("Package3")[0];
if (checkbox1.checked)
{
numberOfCheckedCheckboxes++;
}
if (checkbox2.checked)
{
numberOfCheckedCheckboxes++;
}
if (checkbox3.checked)
{
numberOfCheckedCheckboxes++;
}
alert(numberOfCheckedCheckboxes >= 2);
}
DEMO: JSFiddle
This code isn't the cleanest block of code, however it does get the job done, and will return true if there are at least 2 checkboxes checked, and will return false otherwise. To make it cleaner, you can change the name value of each checkbox to the same name, such as "packages", and then use document.getElementByName("packages"), then use a for-each loop to loop through each element and check its checked state (I would provide a demo in JSFiddle or JSBin, however it seems that Google Chrome is blocking the script in that case). Using the for-each implementation would allow you to use the same amount of code, regardless of the number of checkboxes.
In HTML, you cannot.
You can impose restrictions in client-side JavaScript or in server-side processing of form data, or both. As usual, client-side restrictions are inherently unreliable and should be regarded as convenience to the user, not a reliable method of doing anything. Server-side processing depends on the server-side technology used.

Checkbox onclick not firing

I'm at my wit's end with this.
Can anyone see anything wrong with this line? The function won't fire by clicking on the checkbox for some reason, but the calling function works fine (if I copy the exact "onclick" attribute over to the label for the checkbox, it works fine).
<input type="checkbox" name="match_35_0" id="match_35_0d" value="d0" onclick="checkSwap(document.page_form.match_35_0d, document.page_form.match_35_0)"></input>
If anyone can see why on earth this wouldn't be working, I would really appreciate it.
Thanks!
EDIT: Since a couple people asked, here's the checkSwap function (all it does is throw an alert so I can see that my onclicks are working before I add any code):
function checkSwap(radioid, groupid) {
alert("radio: " + radioid + " group: " + groupid);}
And here's the whole sample of the table cell that the checkbox in question is in (apologies for the formatting, the code sample doesn't seem to want to accept my newlines):
<td><label onclick="checkSwap(document.page_form.match_34_0d,document.page_form.match_34_0)" for="match_34_0">N</label><input type="checkbox" name="match_34_0" id="match_34_0d" value="d1" onclick="checkSwap(document.page_form.match_34_0d, document.page_form.match_34_0)"></input></td>
EDIT: Alright, canceling out a separate function that was limiting the checkboxgroup to 1 checked box was the issue.
The code that does the limiting was setting an onclick attribute for each checkbox, and that is apparently overriding the tag-set attribute. I'll have to figure out how to hack around it.
This syntax
document.page_form.match_35_0d
actually searches in the form with name of page_form for an input element with name of match_35_0d. But you have actually set it as an id of the checkbox where the onclick is definied.
You could solve your problem with the following call in the onclick:
checkSwap(this, document.page_form.match_35_0)
By the way, a checkbox is not the same as a radiobutton and you're actually not passing the ID's to the function, but instead the whole elements. Rewrite your function as
function checkSwap(checkbox, group) {
var checkboxId = checkbox.id;
for (var i = 0; i < group.length; i++) {
var element = group[i];
var elementId = element.id;
// ...
}
// ...
}
To obtain an element by ID, just use Document#getElementById().
var element = document.getElementById('someId');
If JQuery's ready method is already defined then Chek box onclick event do not work. You can fire the event if you add a Jquery click event inside ready. Not sure if this is IE issue ..?
Incase you already have Jquery's ready function then Onclick attribute of the ckeckbox will not fire. You have to add the click event in Jquery. Only then it works
Like below. I don't know the reason.
$('#cbFinalAttest').click(function (event) {
...
}
this function does fire - checked in firebug
<input type="checkbox" name="match_35_0" id="match_35_0d" value="d0" onclick="alert('55')"></input>
you have to check 'checkSwap'
It would be easier to pass in this to the function, then the parameter would be a reference to the element that called the function. So you can do:
function checkSwap(self){
alert(self.id);
}
Edit: Also, document.page_form.match_35_0.id will get the id, not the way you have it.