2

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 ?

1
  • For both drop down? Commented Jan 12, 2017 at 7:41

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.