简体   繁体   中英

How to store all selected values from 2 select boxes into an array with Jquery?

I have 2 select boxies like this:

<div class="info">
    <select name="type" class="data" onchange="getData(this.value);">
        <option value="teacher">Teacher</option>
        <option value="student">Student</option>
    </select>
    <select name="class" class="data" onchange="getData(this.value);">
        <option value="1A">Class 1A</option>
        <option value="1B">Class 1B</option>
    </select>
</div>
<script>
    function getData() {
        var datas = [];
        $.each($('.data'), function (index, value) {
            if ($(value).prop('selected') == true) {
                datas.push($(value).val());
            }
        });
        console.log(datas);
    }
</script>

I want to store all selected values in a array when onchange event called. But my code not working, any help ?

To achieve this using jQuery you can remove the outdated onchange attributes and use unobtrusive JS code to hook your events.

From there you can use map() to build an array from the selected values of all your .data elements. Try this:

 $('.data').change(function() { var selectedValues = $('.data').map(function() { return $(this).val(); }).get(); console.log(selectedValues); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="info"> <select name="type" class="data"> <option value="teacher">Teacher</option> <option value="student">Student</option> </select> <select name="class" class="data"> <option value="1A">Class 1A</option> <option value="1B">Class 1B</option> </select> </div>

You need to use each on .data to get all selected value from drop down. Check below code.

 $(".data").on("change", function () { var datas = []; $(".data").each(function () { datas.push($(this).val()); }) console.log(datas); })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="info"> <select name="type" class="data" > <option value="teacher">Teacher</option> <option value="student">Student</option> </select> <select name="class" class="data"> <option value="1A">Class 1A</option> <option value="1B">Class 1B</option> </select> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM