Submit form after selecting items from multiple dropdown lists - JavaScript

让人想犯罪 __ 提交于 2021-02-08 09:42:43

问题


Here is my HTML

<form action="processForm.html" method="post">
    <label for="InputOne">Input One</label>
    <select id="InputOne">
        <option val="1">Item</option>
        <option val="2">Item</option>
        <option val="3">Item</option>
        <option val="4">Item</option>
    </select>

    <label for="InputTwo">Input Two</label>
    <select id="InputTwo">
        <option val="1">Item</option>
        <option val="2">Item</option>
        <option val="3">Item</option>
        <option val="4">Item</option>
    </select>

    <input type="submit" value="Submit">
</form>

How do I enable the user to select from multiple dropdown lists and then hit a Submit button? I found this answer How to submit form on change of dropdown list?. It's close, but I don't think it's what I want. This will submit after a single dropdown list.


回答1:


The short answer

<form id="my-form" method="post">

    <select name="first-list" multiple="multiple" size="10">
        <option value="0"></option>
        <option value="1">first</option>
        <option value="2">second</option>
        <option value="3">third</option>
    </select>

    <select name="second-list" multiple="multiple" size="10">
        <option value="0"></option>
        <option value="1">first</option>
        <option value="2">second</option>
        <option value="3">third</option>
    </select>

    <!-- use this for client-side processing -->
    <input type="button" name="button" value="submit" />

    <!-- use this for server-side processing -->
    <input type="submit" name="submit" value="submit" />

</form>

EDIT

//  
// Collecting selected items from one or more multiple select-lists 
//
window.onload = function(){
    document.getElementById("button").onclick = function(){
    var lists = document.getElementsByTagName('SELECT'), chosen = [], temp = [], list = {}, i, j; 
    for(i = 0; i < lists.length; i++) {
        list = lists[i];
        temp = [];
        for(j = 0; j < list.length; j++) {
          if(list[j].selected) temp.push(list[j].value);  
        }
        chosen.push(temp);
    }
    console.log(JSON.stringify(chosen));
    // you will have JSON like this [["1","4","5"],["6","7"]]
};

Now, you have a JSON object ready to send on your server. If you have any doubts how to do it, check my previous answer on topic how to send and receive JSON data with JavaScript using POST and GET method.

And check the working fiddle.




回答2:


If I understand correctly. You're having trouble submitting the data from both select dropdown.

I was facing the same problem, but adding enctype='multipart/form-data' to the form class solved it



来源:https://stackoverflow.com/questions/24531815/submit-form-after-selecting-items-from-multiple-dropdown-lists-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!