Post values from a multiple select

前端 未结 2 1996
Happy的楠姐
Happy的楠姐 2020-12-05 03:44

How can I post values from a multiple select in a form? When I hit submit none of the selected values are posted.

相关标签:
2条回答
  • 2020-12-05 04:10

    try this : here select is your select element

    let select = document.getElementsByClassName('lstSelected')[0],
        options = select.options,
        len = options.length,
        data='',
        i=0;
    while (i<len){
        if (options[i].selected)
            data+= "&" + select.name + '=' + options[i].value;
        i++;
    }
    return data;
    

    Data is in the form of query string i.e.name=value&name=anotherValue

    0 讨论(0)
  • 2020-12-05 04:24

    You need to add a name attribute.

    Since this is a multiple select, at the HTTP level, the client just sends multiple name/value pairs with the same name, you can observe this yourself if you use a form with method="GET": someurl?something=1&something=2&something=3.

    In the case of PHP, Ruby, and some other library/frameworks out there, you would need to add square braces ([]) at the end of the name. The frameworks will parse that string and wil present it in some easy to use format, like an array.

    Apart from manually parsing the request there's no language/framework/library-agnostic way of accessing multiple values, because they all have different APIs

    For PHP you can use:

    <select name="something[]" id="inscompSelected" multiple="multiple" class="lstSelected">
    
    0 讨论(0)
提交回复
热议问题