Midori_hige Midori_hige - 4 months ago 6
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">

<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">
<td>ID Producto</td>
<td><input type="text" name="id" value="" /></td>
<td><input type="text" name="nombre" value="" /></td>
<td><input type="text" name="stock" value="" /></td>
<td><input type="text" name="precio" value="" /></td>


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.


You can do this using jQuery as show below:


<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 />

jQuery -

  $('#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/.