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

I searched for the answers here and did not find anything that could directly help me, so I'm going to ask here. I have a form with several selection blocks:

<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, this is the same selection window. I told the client to use select multiple, but he wants it. The user can add as much as needed for these selection fields (so it can be up to 20 blocks of choice at a time), and I need to get the value (1 or 2 or 3) and the text inside the option. This is then an array that I need to destroy, because I need to add the general values ​​of the selection fields in php. I could use jquery to collect values ​​or php, which is ever easier. Thank you in advance for any help!

+4
source share
4 answers

Try this, it will work for dynamically created elements of choice.

 $(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 number of all selected items.

+6
source
 $(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'); on var $select = $('[name="acabados[]"]'); to select only select elements with the acabados[] name attribute.

+2
source

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

+2
source

Why not just give them a different id and make an account in jquery / javascript. Alternatively, give them all the same class and do .each () to capture the values ​​in all of them.

0
source

Source: https://habr.com/ru/post/1391903/


All Articles