checkbox value is not sent in HTTPRequest if unchecked - html

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}

Related

How to validate a text with a custom regex validation with return type as true or false in Angular 7

I am new to Angular development. I have the following requirements.
In case of text field, we need to validate the data entered in the text field with a regular expression with some extra validation. In the .html file, the existing code is like this.
<input type="text" id="domainName" [pattern]="validateDomain()" [placeholder]="ComputeIPAddressMessages.DOMAIN_NAME_PLACEHOLDER" name="domainName" class="form-control"
[(ngModel)]="computeIPAddress.domainName" [disabled]="disabledComponent" #domainNameModel="ngModel"
size="20" required>
<span class="tooltip-content">
{{ComputeIPAddressMessages.INVALID_DOMAIN_NAME}}
</span>
In the corresponding .ts file, the code is like this.
public validateDomain(): any {
return CommonConstants.DOMAIN_NAME_REGEX;
}
There are few new requirements so that I have to strip the contents of the html text and I have to do some manipulations before performing regular expression match.
SO I want to write method like this.
public validateDomain(): any {
// Check if the domain name already exists or not
// If the domain name start with .(period) or -(hyphen), remove it
// Other check
// perform some regular expression validation
// Return either true or false
return true or false;
}
Is it possible in case of Angular 7 ? Please suggest and help me to achieve it. This is the way I want to do custom regex validation instead of directly passing a regular expression.
It is not possible to give extra validations aside from regex patterns in [pattern] or pattern attribute in Angular as per my knowledge. The best way to handle it is using traditional (change) event in the html input tag and corresponding function call from component file. Add a boolean flag isInvalidDomain which will set to true when the pattern along with your conditions after doing your manipulations are not matching and set to false if validations are matching.
sample.html
<input type="text" id="domainName" (change)="validateDomain()" [placeholder]="ComputeIPAddressMessages.DOMAIN_NAME_PLACEHOLDER" name="domainName" class="form-control" [(ngModel)]="computeIPAddress.domainName" [disabled]="disabledComponent" #domainNameModel="ngModel" size="20" required>
<span class="tooltip-content" *ngIf="isInvalidDomain"> {{ComputeIPAddressMessages.INVALID_DOMAIN_NAME}}
</span>
yourcomponent.ts
isInvalidDomain :boolean = false;
validateDomain(){
if(condition1 == true){
if(computeIPAddress.domainName.test(CommonConstants.DOMAIN_NAME_REGEX)){
this.isInvalidDomain = false;
// success condition code
} else {
this.isInvalidDomain = true;
}
} else {
this.isInvalidDomain = true;
}
}

Checkbox always returning null in jsp

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

Redirect to URL using code in GET form

I am working on a project in Squarespace to create a very basic combination lock form where inputting different codes (invoice #'s) takes you to specific URLs. Because it is Squarespace, I don't think I have very many options for coding other than html (but I could be wrong - I'm very much in learning-mode!!).. I did find a similar question here Query String Redirection: How to change form input to URL?, but how to implement the response into squarespace's code block is way beyond me...
Right now my code looks like this:
</span></p>
<div style="margin-top:5px;">
<form method="GET" action="/our-team/bob">
<div class="input-append">
<input class="span2" id="appendedInputButton" name="code" type="text">
<button class="btn btn-primary" type="submit">Submit!</button>
</div>
</form>
</div>
Using this code, the form takes you to the our-team/bob page every time, regardless of what is entered into the form. e.g. if 0000 is entered into the form, I am redirected to www.mydomain.com/our-team/bob?code=0000 -- which is still just the our-team/bob page; if 1234 is entered into the form, I am redirected to www.mydomain.com/our-team/bob?code=1234 --- which is still just the our-team/bob page; and if nothing is entered into the form and I click submit, it still redirects me to the our-team/bob page.
Ideally, each unique code will bring me to a unique page that I have developed. But squarespace doesn't let me use a "?" in a page url, so I can't just redirect that way. I would like to be able to enter a specific code that takes me to a corresponding page and need to check the code against an array with some simple logic like this:
If string is 1234, go to /our-team/bob
If string is 5555, go to /our-team/jane
If string is 0000, go to /our-team/allen
(etc.)
If string is anything else, show an error and not leave the page at all OR go to some sort of error page.
Hopefully this makes sense (and hopefully it is possible to do!) Please let me know if there is any other information I can provide you with. Your help is VERY much appreciated!
What you are asking for is not possible with HTML and standard HTTP protocol. The form values are either sent as query string parameters (if you are using GET) or as part of the request body (if you are using POST). Here you seem to be asking to make some mapping between the value entered by the user and the specific page being called on the server. The only way to achieve that is to use some javascript. Subscribe to the onsubmit event of the form and write the mapping between the client value and the server one:
<form method="GET" action="/our-team/bob" onsubmit="return handleSubmit();">
...
</form>
and then you could define the handleSubmit function to implement your custom logic:
<script>
var handleSubmit = function() {
var value = document.getElementById('appendedInputButton').value;
if (value === '1234') {
window.location.href = '/bob';
} else if (value === '5555') {
window.location.href = '/jane';
} else if (value === '0000') {
window.location.href = '/allen';
} else {
window.location.href = '/some-default-page';
}
return false;
};
</script>

Save input data to localStorage on button click

I am trying to build my first web application. In my app I need to have a settings panel, but I have no idea how to do it. I've been searching the web and came across a HTML5 localStorage, which I believe might be the best way to do the things. But the problem is I have no idea how to use it.
<input type='text' name="server" id="saveServer"/>
How can I save data from input to localStorage when user clicks the button? Something like this?
<input type='text' name="server" id="saveServer"/>
<button onclick="save_data()" type="button">Save/button>
<script>
function saveData(){
localStorage.saveServer
}
</script>
The localStorage object has a setItem method which is used to store an item. It takes 2 arguments:
A key by which you can refer to the item
A value
var input = document.getElementById("saveServer");
localStorage.setItem("server", input.val());
The above code first gets a reference to the input element, and then stores an item ("server") in local storage with the value of the value of that input element.
You can retrieve the value by calling getItem:
var storedValue = localStorage.getItem("server");
This worked for me. For setting I placed .value behind the var and called the var in the setItem:
var input = document.getElementById('saveServer').value;
localStorage.setItem('server', input);
For getting the text back:
document.getElementById('saveServer').value = localStorage.getItem('server');

Play framework get form value

I have a form with an accept button and a reject button. When a user presses the accept button I want the value of accepted in my database to contain the value true. If the user presses reject then I want the value of accepted in my database to contain the value false. The code I have below does not work. Are there any suggestions on how I can get this working properly?
public static void acceptOrRejectResponseForm(Long id,String accept,String reject) {
Response responseForm = Response.findById(id);
if(accept != null && !accept.isEmpty()){
responseForm.accepted = true;
}
else if(reject != null && !reject.isEmpty()){
responseForm.accepted = false;
}
accepted.save();
}
This my html
<form action="#Admin.acceptOrRejectResponseForm(response.id)" method="GET">
<input type="submit" value="accept" name="accept">
<input type="submit" value="reject" name="reject">
don`t create two submit buttons.
Create two hidden fields with default value 0. Call name accept and reject. Than create two buttons with onclick action. If you click on accept button with the onclick action you just set the hidden field accept on 1 and reject on 0. When you click reject button you set hidden accept field on 0 and reject on 1. Than you make submit for the form in js. In the code get those two fields and check witch one is set for 1 and witch one is set to 0. That way you can set it in db