Hi,

I have a jsp which contains a list of radio buttons. I want that when the user selects any one of them the value of the corresponding radio button be passed to a textbox on the same page.

How would I do that, I have no idea.

Please help!!!!!!!!!It's urgent.

Thanks a ton in advance

Saswati

Dani AI

Generated

Short answer: handle it on the client with JavaScript so the textbox updates immediately when a radio is selected. That follows the direction given by and , and is a bit cleaner than using a form submit as mentioned — attach change handlers to the radio group so the textbox is updated as soon as the user picks one.

Example (unobtrusive, works with radios generated by JSP):

<!-- radios (rendered by JSP) -->
<label><input type="radio" name="choice" value="Option 1"> Option 1</label>
<label><input type="radio" name="choice" value="Option 2"> Option 2</label>
<input type="text" id="selectedValue" />

<script>
document.addEventListener('DOMContentLoaded', function() {
  var textbox = document.getElementById('selectedValue');
  var radios = document.querySelectorAll('input[type=radio][name=choice]');
  for (var i = 0; i < radios.length; i++) {
    radios[i].addEventListener('change', function() {
      if (this.checked) textbox.value = this.value;
    });
  }
});
</script>

Quick troubleshooting and tips:

  • Make sure every radio in the group shares the same name and each has a value attribute.
  • If the script runs too early, wrap it in DOMContentLoaded (as above) or place it after the form.
  • For radios added later (AJAX), use event delegation on a container instead of binding once.
  • If supporting very old browsers, replace forEach/querySelectorAll usage with a classic loop (example uses a loop).

For reference on event handling see EventTarget.addEventListener.

Recommended Answers

All 4 Replies

Javascript. most likely. Ask on the JavaScript Forum.

You can use a java script function in the jsp page like


<form method = ......jsp onSubmit=ReadRadioButton()>

And in ReadRadioButton() , you can write the code needed to read the value.

Yes, script is the only way you are going to get this behavior. With straight JSP it would require a post to the server and redisplay of the new page.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.