I want to do a very simple task. I want to have a drop box and display (in the same page) the user input as soon as the user makes his choice. There must be no button involved. I dunno how to pass the values of the forms w/o using a submit button.

Dani AI

Generated

A quick, practical summary that ties the thread together: was pointing in the right direction — handle the select's change on the client. found a server-side submit-on-change worked, but that forces a full page reload. Two cleaner options are shown below: update the page immediately with client-side DOM code, or send the selection to the server asynchronously so JSP can respond without reloading.

Client-only (no server contact)
This reads the select value in the browser and writes it into a page element immediately.

<select id="choiceSelect">
  <option value="">Choose...</option>
  <option value="apple">Apple</option>
  <option value="banana">Banana</option>
</select>

<div id="result"></div>

<script>
document.getElementById('choiceSelect').addEventListener('change', function(e) {
  document.getElementById('result').textContent = e.target.value;
});
</script>

AJAX to JSP (no full reload)
If you need server-side processing, post the value asynchronously and insert the server response into the page.

<script>
document.getElementById('choiceSelect').addEventListener('change', function(e) {
  var v = encodeURIComponent(e.target.value);
  fetch('/handleChoice', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: 'choice=' + v
  })
  .then(function(r){ return r.text(); })
  .then(function(html){ document.getElementById('result').innerHTML = html; })
  .catch(console.error);
});
</script>

Tips: keep a normal form submit as a non-JS fallback, prefer JSON for structured responses, encode values with encodeURIComponent, and beware of CORS if the endpoint is on another origin. See MDN for addEventListener and Using Fetch.

Recommended Answers

All 4 Replies

there might be a way in javascript. like <select onchange="Jsmethod()">

there might be a way in javascript. like <select onchange="Jsmethod()">

I tried working on the onchange but the problem is what do I put in the Jsmethod since I don't know how to access the data in the dropbox. The "request.getParameter()" doesn't work.

can you put it in a form and just say form.submit when it changes?

can you put it in a form and just say form.submit when it changes?

Thanks for the suggestion. I found a JSP counterpart of that Javascript command. it's onchange=submit();

Thanks a lot. ^^

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.