0

I have small html calculator, where you can enter two numbers, with two separate buttons to either add or subtract them, like this:

<form method="post" action="<%= actionURL %>" >
    <input type="text" name="x" value="${x}"/>
    <input type="text" name="y" value="${y}"/>
    <input type="submit" name="add" value="add"/>
    <input type="submit" name="subtract" value="subtract"/>
</form>

I would like to replace the two buttons with a select element, that would submit the form when the user chooses one of the options. So far I have the following:

<form method="post" action="<%= actionURL %>" >
    <input type="text" name="x" value="${x}"/>
    <input type="text" name="y" value="${y}"/>
    <select name=operation onChange="this.form.submit()">
        <option value="add">Add</option>
        <option value="subtract">Subtract</option>
    </select>
</form>

Now I get a dropdown box with the options "Add" and "Subtract". Whenever I choose "Subtract", the form gets submitted, and I can check the operation parameter of the request back on the server. But clicking on the dropdown box and then on "Add" doesn't fire the onChange event, since "Add" is already selected, and so the form is not submitted. Is there any way I can submit the form, when the user chooses the already selected option?

Boris
  • 5,094
  • 4
  • 45
  • 71
  • 1
    This might help you: http://stackoverflow.com/questions/647282/is-there-an-onselect-event-or-equivalent-for-html-select. (Essentially you're looking for a way to fire an event on selection, not change.) – Andrew Cheong Jun 14 '13 at 12:35
  • Please consider selecting an answer or add more specific information if none of the answers satisfy your question. – Alexander Ivanov Jul 10 '13 at 10:59

2 Answers2

3

This happens because "Add" is already selected and no change happens. You should add another element to the select:

<form method="post" action="<%= actionURL %>" >
    <input type="text" name="x" value="${x}"/>
    <input type="text" name="y" value="${y}"/>
    <select name=operation onChange="this.form.submit()">
        <option value="" disabled="disabled" selected="selected">Select operation</option>
        <option value="add">Add</option>
        <option value="subtract">Subtract</option>
    </select>
</form>
Alexander Ivanov
  • 717
  • 4
  • 16
1

You can use a submit button to submit the form where you can set operation parameter depeding upon what value is selected in dropdown and can perform operation..

Priya Prajapati
  • 304
  • 1
  • 4
  • 10