Java Spring with thymeleaf checkbox non checked is Empty instead of false - java

I have checkbox inside of my form :
<div class="form-check form-check-inline">
<input type="checkbox" th:field="${search.titleIncl}" />
<label class="form-check-label" th:for="${#ids.next('covered')}">Title</label>
</div>
This checkbox by default should be on since search object has this value assigned as true. This works fine. What i expected from thsi checkbox is to send either true or false when its checked/unchecked. What i got now is True if its checked and nothing when not checked. That his a bit of an issue for me :
In controller:
#GetMapping(value = Utils.MAPPING_INDEX)
public ModelAndView index(#RequestParam("titleIncl") Optional<Boolean> titleIncl) {
...calling fillSearch inside of body....
}
private Search fillSearch(Optional<Boolean> titleIncl..) {
Search search = new Search();
//Get seach value if nothing provided give me default.
search.setTitleIncl(titleIncl.orElse(search.isTitleIncl()));
...
return search;
}
Whole point of this form is to get user select what parts of the object he wants to search :
So if he unselects checkbox and i dont send FALSE in optional, I run into problem.
When user initialy goes into the site, he doesnt send any of these parameters so it behaves fine by setting everything to true.
Bud once he initiates search and deselects parts he doesnt wanna search in, he still ends up with defaults and searches in everything.
So is there a simple way of sending Optional FALSE if checkbox value is not selected?
Note :
By simple i mean without creating additional endpoint for this form search and no Javascript :)
And yes the form is under GET request

No matter what you do , only checked checkboxes are sent to server, not unchecked one.You have to code it in server to handle unchecked checkboxes.
https://www.w3.org/TR/html401/interact/forms.html#form-controls
Checkboxes (and radio buttons) are on/off switches that may be toggled
by the user. A switch is "on" when the control element's checked
attribute is set. When a form is submitted, only "on" checkbox
controls can become successful.
But with the thymeleaf you can try like below ,
<ul>
<li th:each="feat : ${allFeatures}">
<input type="checkbox" th:field="*{features}" th:value="${feat}" />
<label th:for="${#ids.prev('features')}"
th:text="#{${'seedstarter.feature.' + feat}}">Heating</label>
</li>
</ul>
which will produce below html ,
<ul>
<li>
<input id="features1" name="features" type="checkbox" value="SEEDSTARTER_SPECIFIC_SUBSTRATE" />
<input name="_features" type="hidden" value="on" />
<label for="features1">Seed starter-specific substrate</label>
</li>
<li>
<input id="features2" name="features" type="checkbox" value="FERTILIZER" />
<input name="_features" type="hidden" value="on" />
<label for="features2">Fertilizer used</label>
</li>
<li>
<input id="features3" name="features" type="checkbox" value="PH_CORRECTOR" />
<input name="_features" type="hidden" value="on" />
<label for="features3">PH Corrector used</label>
</li>
</ul>
Don’t worry about those hidden inputs with name="_features": they are
automatically added in order to avoid problems with browsers not
sending unchecked checkbox values to the server upon form submission.
More on,
https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#checkbox-fields

Related

How to keep dynamicly added controls ater postback? Javascript, JSP

Good Morning all. I have an issue that I am trying to solve but I am stuck, partially due to me not having a full understanding of JSP/ Java platform, and not having a full understanding of what/ how to implement my code in the right way. I do have an ASP background, so I am a bit familiar with some concepts.
The issue I am running into is: I am trying to populate a dynamic label and text box to appear on a webpage (JSP). I have successfully been able to populate the textboxes with a piece of JavaScript code, however, when I submit the form (on Postback) my dynamic controls are gone but all of my static controls are still present. I need to find a way to keep my information in the dynamic control on submit as well. The form does not submit when I have errors but when the form finish rendering all information and dynamic text are all lost.
My Solution: I have decided to use hidden fields to hold this information but I am unable to fire off the hidden fields after form submit: Please have a look below
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript">
function validateForm(){
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="" && document.getElementById('two').value==1){
alert("EMPTY");
document.getElementById('text').style.display = "block";
return false;
}else{
document.myform.submit();
}
}
function display(el) {
if (el.value == "two") {
document.getElementById('text').style.display = "block";
}else {
document.getElementById('text').style.display = "none";
document.getElementById('dynbox').value = '';
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
<label >First Name</label> <input type="text"/>
<div>
<input type="radio" name="radio1" id="one" value="one" onchange="display(this);"/>Eligible
</div>
<div>
<input type="radio" name="radio2" id="two" value="two" onchange="display(this);"/>Not Eligible
</div>
<div id="text" class="glassy" name="mytext" style="display:none;">Other: <input type="text" id="dynbox"/>
</div>
<div>
<input type="hidden" name="mytext" value="${mytext}" />
<br></br>
<input type="submit" onclick="validateForm()" value="Submit"/>
</div>
</form>
</body>
</html>
What I am trying to do is select the "Not Eligible" option and type some text in the text box 'mytext' then press submit. Once I press submit, and if the First Name textbox is not filled in, then I want to trigger my hidden textbox so that I won't loose my information in my dynamically created textbox.
I hope this makes sense. I am not sure of how to do in JSP. Can someone give guidance on how to get my expected results? Keeping dynamic controls after Postback?
Thanks in advance.
One thing first: don't let the names Java and Java-Script confuse you. They have (almost) nothing in common. What you are using here is Java-Script only (no Java, no JSP anywhere).
Anyway, I think it is the condition in your validateForm() function that does not work.
I tested it a little bit and it works with these changes:
your form
<form name="myForm" action="test.html" method="get" onsubmit="return validateForm();">
<label >First Name</label> <input type="text" id="firstName"/>
<div>
<input type="radio" name="radio1" id="one" value="one" onchange="display(this);"/>Eligible
</div>
<div>
<input type="radio" name="radio2" id="two" value="two" onchange="display(this);"/>Not Eligible
</div>
<div id="text" class="glassy" name="mytext" style="display:none;">Other: <input type="text" id="dynbox"/>
</div>
<div>
<input type="hidden" name="mytext" value="${mytext}" />
<br></br>
<input type="submit" value="Submit"/>
</div>
</form>
I simply changed the first input and gave it an ID (since I couldn't find the id 'fname' anywhere), so we can access it with JavaScript.
The next thing is your submit button. You had an additional onclick="validateForm()"; there – which indeed calls the validateForm function but does not listen to the returned value (it executes the function.. nothing more). So the onsubmit="return validateForm()" is enough.
your validate function
function validateForm() {
var x = document.getElementById('firstName').value;
if ((x == null || x == "")) {
alert("EMPTY");
// document.getElementById('text').style.display = "block";
return false;
} else {
return true;
}
}
x can now be retrieved by the element's id (which I find easier).. Anyway, the if condition was one of the problems. In your form you set the value of your radio button 'two' to two. But in the if condition you ask if could be 1... which (in my understanding) should never happen. I just removed it to show you that your function works like this. If you want to check the state of the second radio button, you can test it like this:
if(document.getElementById('two').checked == true)
or even better
if(document.getElementById('two').checked)
one last thing: in your else statement, you can simply return true instead of calling submit.. because here:
onsubmit="return validateForm();"
you ask your validateForm() function to give you either true and then submit or false and then stop submitting.
Oh, one last thing (it'S the last, promise): Java and Java-Script handle all && and || in the order: first ´x==null´ would be tested and then x=="" && document.getElementById('two').value==1 would be evaluated together (&& has a stronger binding than ||).. Just for your information :)

Wicket: Two AjaxButtons inside separate forms issue

I want to place two separate file upload panels on page, one is for images, another for other files. Each panel contains a form with AjaxButton inside. First I developed the first panel, it worked as expected. But when I added another one, the second AjaxButton inside a form is not responding when clicked. Instead, when I click on the first button, the second one responds. What could be the reasons for that?
Here's the first panel's HTML:
<wicket:panel>
<div wicket:id="form-container-img">
<form wicket:id="form-img">
<img wicket:id="releaseImage" class="thumbnail" />
<p>
<label>Select file :</label>
<input wicket:id="fileUpload-img" size="40" type="file"/>
<input wicket:id="uploadButton-img" id="uploadButton" type="submit" value="Upload" />
</p>
</form>
</div>
</wicket:panel>
And the second one:
<wicket:panel>
<div wicket:id="form-container-album">
<form wicket:id="form-album">
<span wicket:id="releaseName" />
<p>
<label>Select file :</label>
<input wicket:id="fileUpload-album" size="40" type="file" />
<input wicket:id="uploadButton-album" id="uploadButton" type="submit" value="Upload" />
</p>
</form>
</div>
</wicket:panel>
So now, when both panels are in place, clicking uploadButton-album does nothing but it responds by clicking uploadButton-img.
EDIT:
<wicket:panel>
<div wicket:id="uploadPanelReleaseImg"></div>
<div wicket:id="uploadPanelReleaseAlbum"></div>
</wicket:panel>
In html markup, the id attribute should always be unique on the page. I'm not sure it's required by any spec, but it's generally regarded as good practice, and things tend frequently to depend on it.
If you need to control the id (because you're referencing it in JavaScript and it's easier than figuring out what id Wicket generated), you need to manage this manually.
If you simply omit the id attribute, Wicket will generate one based on the wicket id, and guarantee uniqueness on the page.
Based on the comment thread, this appears to have been the problem.

How to send label parameter from JSP to servlet?

I have a jQuery dialogue box which contains values as checkboxes. On selecting the checkboxes I am storing the selected values into label. Next I have to send these values from label as parameter through form to servlet but I don't know how to complete it.
Here is my code:
<form action="CallTimer" method="GET">
<label class="button2">Set Date: </label>
<input type="text" name="date" id="date" size="4">
<input type="Submit" name="Submit" value="Submit" id="Submit">
<br/>
Select Reporting Level
<label class="button2" style="display:none" id="depart"> Department</label>
</form>
I am retrieving these parameters in my Servlet as:
String reportname=request.getParameter("depart");
System.out.println(reportname);
But it is returning null values. Please help me.
Thanks in advance.
You have to use hidden input field:
<input type="hidden" name="depart" />
You need to understand what gets passed on form submission and what is not. In a nutshell, only values of the input fields get sent to the server. You have several ways to solve your problem:
Write value to a hidden input field
Modify the query string (what gets sent after ? in your GET request) during form submission (using java script):
?...&depart=xxx

How do I determine radio button selection based on value using selenium webdriver?

I am trying to determine which of two radio buttons is selected and based on that select the other one. I'm using Java and selenium.
My HTML is:
<div class="row span-670px">
<h3>Turn on</h3>
<div class="field-row">
<div class="field-wrap radio-row clearfix ">
<input type="radio" name="choosePaymentModel" value="QUOTEHOLD" checked="checked" />
<label>
...
</label>
</div>
</div>
<div class="row last span-670px">
<h3>Turn off</h3>
<div class="field-row">
<div class="field-wrap radio-row clearfix ">
<input type="radio" name="choosePaymentModel" value="BASIC" />
<label>
...
</span>
</label>
</div>
</div>
The only thing that differs is the value attribute. The checked attribute will change based on which one is checked, so the only clear way to differentiate the two is by value. I can't seem to find the proper syntax to grab the correct radio buttons. When utilizing the IDE, the element identifiers swap out with each other depending on the selection so nothing is every unique.
Suggestions?
I had to use:
element = driver.findElement(By.xpath("//input[#name='choosePaymentModel' and #value='QUOTEHOLD']"));
and
element = driver.findElement(By.xpath("//input[#name='choosePaymentModel' and #value='BASIC']"));
to determine which was selected, but unfortunately the click methods did not work on them.
When playing with the IDE was lucky enough to find two separately bizzare elements to click on, which were not in fact elements that contained the "isSelected" values.
In either case, looks like I found the answer to my own problem.
String tempvalue[]=object.split(Concrete.VALUE_SPLIT);
//here I am splitting the values passed through data sheet against radio buttons
String Val_radio =Browser.driver.findElement(By.xpath(OR.getProperty(tempvalue[0])+data+OR.getProperty(tempvalue[1]))).getAttribute("value");
System.out.println(Val_radio);
Boolean radio = Browser.driver.findElement(By.xpath("//input[#name='radio' and #value="+"'"+Val_radio+"'"+"]")).isSelected();
if(radio.booleanValue()==true){
//do something here
}

Java/HTML form with a multiple checkbox "All of the above" option

I have an HTML form which posts its information to a java servlet. One of the sections in the HTML is a multiple checkbox where one of the options is an "all of the above" option.
Mode of Transportation:<br>
<input type="checkbox" name="transport" value="Car" /> Car <br>
<input type="checkbox" name="transport" value="Bike" /> Bike <br>
<input type="checkbox" name="transport" value="Public Transit" /> Public Transit <br>
<input type="checkbox" name="transport" value="All of the Above" /> All of the Above <br>
The java page accepts it into an array:
String[] transport = request.getParameterValues("transport");
And now it's supposed to just post back the information: How do I account for the "All of the Above" option? Meaning if it's checked how do I forgo the other checks and list everything?
Two ways:
Either using javascript, check all the check boxes if All Of the above is selected immediately after select or before posting the form.
Or handle in the server side i.e. before processing, check, if one of the values is All Of the above then handle it appropriately i.e. populate your user answer list with all options provided.
You use statement below to check if All Of the above was selected:
boolean isAllSelected = Arrays.asList(transport).contains("All Of the above");
Instead of having a value by the name All of the Above
<input type="checkbox" name="transport" value="All of the Above" /> All of the Above <br>
You can use a select all as described here.
How to implement "select all" check box in HTML?

Categories