Get values from multiple select boxes with same name? Including its value with jquery and php

不问归期 提交于 2019-12-19 08:21:26

问题


I have looked for answers on here and have not found anything that directly can help me so I am going to ask here. I have a form with multiple select boxes:

<select name="acabados[]">
<option value="1">ABC</option>
<option value="2">DEF</option>
<option value="3">GHI</option>
</select>

<select name="acabados[]">
<option value="1">ABC</option>
<option value="2">DEF</option>
<option value="3">GHI</option>
</select>

As you can see they are the exact same select box. I have told the client to use select multiple but he wants it this way. The user can add as many as these select boxes as they desire (so it could be up to 20 select boxes at a time) and I need to get the value (1 or 2 or 3) and the text inside the option. It is then an array that I need to break down cause I need to add the total values of the select boxes in php. I could either use jquery for collecting the values or php, which ever is easier. Thank you in advance for any help!!


回答1:


Try this, it will work for dynamically created select elements too.

$(document).on('change', 'select[name="acabados[]"]', function(){
    var total = 0;
    $('select[name="acabados[]"]').each(function(){
        total += parseInt($(this).val());
    });
});

total var will contain the total of all the select elements selected value.




回答2:


$(function () {
    var $select = $('select');
    $select.on('change', function () {
        var output = 0;
        for (var i = 0, len = $select.length; i < len; i++) {
            output += parseInt($select.eq(i).val());
        }
        //the `output` variable now contains the addition of all the values from the `acabados[]` select elements
    });
});

Here is a demo: http://jsfiddle.net/aPXXA/1/

You can change var $select = $('select'); to var $select = $('[name="acabados[]"]'); to only select the select elements with the acabados[] name attribute.




回答3:


If you want to retrieve the values in PHP, you can just use $_POST['acabados'] and it will contain all the values selected in each menu. See a demo. As long as you include the [] after the name, it will compound all the values for any element with that name into a single array. You can even mix select menus, inputs, and textareas together!




回答4:


Why not just give them different id's and do the count in jquery/javascript. Alternatively give them all the same class, and do .each() to grab the values in all of them.



来源:https://stackoverflow.com/questions/8931368/get-values-from-multiple-select-boxes-with-same-name-including-its-value-with-j

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