Reputation: 585
I am creating a web interface in jsp. I have a java String variable (let's call it 'a') and some radio buttons, and I am trying to get the value of the checked one on click (without submiting the form) and give it's value to the variable.
I made a research on weather this can be done using only jsp and I could not find anything. So I assumed that I have to do this using Javascript. I am new in Javascript(so please excuse me if my question is stupid), but I wrote the following code.
HTML:
`<input type="radio" name="phase" value="value1" class="checkboxes" id="design_phase" onclick="getRadioValue(this.id)" />Value1
<input type="radio" name="phase" value="value2" class="checkboxes" id="development_phase" onclick="getRadioValue(this.id)" checked/>Value2`
Javascript:
`function getRadioValue(id) {
var radioBtn = document.getElementById(id);
if(radioBtn.value=="value1"){
alert(radioBtn.value);
<%a="value1";
System.out.println("value1!");%>
}
else{
alert(radioBtn.value);
<%a="value2";
System.out.println("value2!");%>
}
}`
When I run this, both System.out contents are printed just when I load the page, before I even choose a checkbox. I have put the alert functions in order to make sure that javascript reads the values correctly, and it does indeed! So the problem seems to be with using js together with jsp.
Does anyone know what I am doing wrong, and how can this be done correctly?
Thanks in advance!
Upvotes: 0
Views: 1500
Reputation: 1662
You should use AJAX (if you dont want to submit the form).
This is the methodology:
As soon as the user selects a radio button, an AJAX call is triggered that sends a request to a servlet. The servlet recuperates the option selected from the radio buttons (from the request object) and using this value it generates a response containing the values you want to display in the select (perhaps the values are stored in an array) and then sends the response to the client. The response is received and the values to be displayed in the select are recuperated and dynamically added to the DOM.
Have a look at this link for an explanation of how to do it: How to use Servlets and Ajax?
also here is a very simple example: Return JSON from one JSP to another?
Upvotes: 1