Search code examples
javascriptjavajqueryjspradio-button

Make changes to records using radio buttons.


How can I change and update a list of records using radio buttons? I have a list of student objects(studentList) which is displayed in the UI as follows:

enter image description here

So now I change the grades of Tom and Sally and hit "Update". How do I pass these information back to my servlet?

public class Student{
    private String name;
    private String grade;
    //getters setters
}

I was able to implement the update feature using text field but radio buttons seem tricky.

I use c:forEach to iterate through list of students.

 <c:forEach var="student" items="${studentList}">
    <tr>
        <td>Tom</td>
        <td>
            <label for=""><input type="radio" name="tom" checked="checked"/>A</label>
            <label for=""><input type="radio" name="tom"/>B</label>
            <label for=""><input type="radio" name="tom"/>C</label>
            <label for=""><input type="radio" name="tom"/>D</label>
        </td>
    </tr>
    <tr>
        <td>Sally</td>
        <td>
            <label for=""><input type="radio" name="sally" checked="checked"/>A</label>
            <label for=""><input type="radio" name="sally"/>B</label>
            <label for=""><input type="radio" name="sally"/>C</label>
            <label for=""><input type="radio" name="sally"/>D</label>
        </td>
    </tr>
    .
    .
    .
    <tr></tr>

<button type="submit">Update</button>

Solution

  • You need to give a value to each radio button. For example:

    <!-- Using a single example -->
    <!-- fixed the label issue in your HTML -->
    <input type="radio" id="tom_A" name="tom" value="A" /> <label for="tom_A">A</label>
    <input type="radio" id="tom_B" name="tom" value="B" /> <label for="tom_B">B</label>
    

    Then, in your servlet, you will recover its value using request.getParameter:

    String tomCalification = request.getParameter("tom");
    System.out.println(tom);
    //will print A if selected radio button with A
    //will print B if selected radio button with B
    

    Similar for all other cases.