Midori_hige Midori_hige - 6 months ago 10
Java Question

How to validate when RadioButton is selected?

I'm trying to validate when I select a radiobutton inside a JSP form and make the selection refresh my page with the content I want. I'm planning to use these radiobuttons as a way of selecting categories.

This is my form code:

<form name="login" action="procesarAdd.do">
<br>

<b>CATEGORIA</b>
<br>
<input type="radio" name="g1" value="per" checked="checked" />PERFUME
<input type="radio" name="g1" value="joy" />JOYAS
<input type="radio" name="g1" value="car" />BOLSO CARTERAS

<table border="1">
<tbody>
<tr>
<td>ID Producto</td>
<td><input type="text" name="id" value="" /></td>
</tr>
<tr>
<td>Nombre</td>
<td><input type="text" name="nombre" value="" /></td>
</tr>
<tr>
<td>Stock</td>
<td><input type="text" name="stock" value="" /></td>
</tr>
<tr>
<td>Precio</td>
<td><input type="text" name="precio" value="" /></td>
</tr>
</tbody>
</table>

<br>


I need to show different images depending on the selection of the radio button, and then take all the information on the form to create a new product into a DataBase. I have no knowledge of JavaScript and I'm wondering if this can be done with plain Java or html.

Answer

You can do this using jQuery as show below:

HTML -

<form id="myForm">
  <input type="radio" name="radioName" value="1" /> 1 <br />
  <input type="radio" name="radioName" value="2" /> 2 <br />
  <input type="radio" name="radioName" value="3" /> 3 <br />
</form>

jQuery -

$(function(){
  $('#myForm input').on('change', function() {
   alert($('input[name=radioName]:checked', '#myForm').val()); 
  });
});

Instead of displaying the alert, now you can call whatever AJAX request you want to make or whatever function call you wish to make to your backend.

You can experiment more on this here: http://plnkr.co/edit/gist:2006604?p=preview. You can read more about jQuery's :checked pseudo-class here: https://api.jquery.com/checked-selector/.