Alexander
Alexander

Reputation: 111

JQuery: add selected values in array

I am trying to get the values ​​of selected elements, add them to an array and send. But my code is not working.

<link rel="stylesheet" href="https://res.cloudinary.com/dxfq3iotg/raw/upload/v1569006288/BBBootstrap/choices.min.css?version=7.0.0">
<script src="https://res.cloudinary.com/dxfq3iotg/raw/upload/v1569006273/BBBootstrap/choices.min.js?version=7.0.0"></script>
<div class="row d-flex justify-content-center mt-100">
  <div class="col-md-6">
    <select id="choices-multiple-remove-button" multiple>
      <option value="Acupuncturist" /> Acupuncturist</option>
      <option value="Holistic Care" /> Holistic Care</option>
      <option value="Naturopathic Doctor" /> Naturopathic Doctor</option>
    </select>
  </div>
</div>
$(document).ready(function() {
  var multipleCancelButton = new Choices('#choices-multiple-remove-button', {
    removeItemButton: true,
  });
});

$('#scrape').on('click', () => {
  var brands = $('#choices-multiple-remove-button option:selected');
  var specialty = [];
  $(brands).each(function(index, brand) {
    specialty.push([$(this).val()]);
  });
  console.log(specialty);

  $.post('/wellness', { 'specialty': specialty }, (res) => {});
});

Upvotes: 0

Views: 151

Answers (1)

Carsten Massmann
Carsten Massmann

Reputation: 28196

I prepared the following snippet along the lines of Andreas's and Mosh Feu's comments. Maybe you can explain, what it is that does not work here?

(I commented out the $.post() part as this will not work in an SO snippet.)

$(document).ready(function() {
  var multipleCancelButton = new Choices('#choices-multiple-remove-button', {
    removeItemButton: true,
  });
});

$('#scrape').on('click', () => {
  var brands = $('#choices-multiple-remove-button option:selected');
  var specialty = [];
  brands.each(function(index, brand) {
    specialty.push($(this).val());
  });
  console.log(specialty);
  // $.post('/wellness', { 'specialty': specialty }, (res) => {});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://res.cloudinary.com/dxfq3iotg/raw/upload/v1569006288/BBBootstrap/choices.min.css?version=7.0.0">
<script src="https://res.cloudinary.com/dxfq3iotg/raw/upload/v1569006273/BBBootstrap/choices.min.js?version=7.0.0"></script>
<div class="row d-flex justify-content-center mt-100">
  <div class="col-md-6">
    <select id="choices-multiple-remove-button" multiple>
      <option value="Acupuncturist" /> Acupuncturist</option>
      <option value="Holistic Care" /> Holistic Care</option>
      <option value="Naturopathic Doctor" /> Naturopathic Doctor</option>
    </select>
  </div>
  <button id="scrape">scrape</button>
</div>

Upvotes: 2

Related Questions