DewinDell
DewinDell

Reputation: 1028

Select from multiple HTML fields then add total to another list

I have 3 HTML fields: a textbox and two select lists. What I'm trying to do is let the user enter something in the text field and choose options from the other two lists and then click an "Add" button which adds his total selection to another list. This final list is the one to be submitted and received by the CGI script.

So for example a user types in "Toyota" and selects Sedan from one list and 2004 from a second list and clicks add. Then, "Toyota Sedan 2004" would be added to an empty list. The user can add multiple selections to the list or remove from the list. And this list is the one that is submitted when the form is submitted. It is preferable if I do this in Javascript only so no JQuery. Can anyone point me in the right direction?

Upvotes: 0

Views: 584

Answers (2)

manji
manji

Reputation: 47978

What you need is, when the "add" button is clicked, a simple javascript function is called that retrieves: the text, selection1 & selection2 => build a new option with these information the append it to the result list.

Key javascript functions:

- document.getElementById
- document.createElement
- appendChild

In your html the form/submit button must be around your result list only.

Example (jsfiddle link):

<html>
    <head>
        <script>
            function add() {
                var txt = document.getElementById("txt").value;
                var sel1 = document.getElementById("sel1").value;
                var sel2 = document.getElementById("sel2").value;
                var result = txt + " " + sel1 + " " + sel2;

                var resultOption = document.createElement("option");
                resultOption.value = result;
                resultOption.text = result;
                document.getElementById("selResult").appendChild(resultOption);
            }
        </script>
    </head>
    <body>
        <input id="txt" type="text" />
        <select id="sel1">
            <option value="value11">value11</option>
            <option value="value12">value12</option>
            <option value="value13">value13</option>
        </select>
        <select id="sel2">
            <option value="value21">value21</option>
            <option value="value22">value22</option>
            <option value="value23">value23</option>
        </select>
        <input type="button" value="add" onClick="javascript:add()"/>
        <br/>
        result:
        <form action ="." method="post">
            <select id="selResult"></select>
            <input type="submit" value="submit"/>
        </form>
    </body>
</html>

Upvotes: 1

RDK
RDK

Reputation: 4560

Use need to user this jquery plugins:

  1. Jquery Forms
  2. Jquery Auto Tab
  3. Jquery UI

And some jquery functions that can be useful for you:

  1. .ajax()
  2. prepend()
  3. .on()

Upvotes: 0

Related Questions