how to get each variable in one line

3741 views jquery
3

<div class="auswahl">
    <select id="1Riegel">
        <option value="Mix">Mix</option>
        <option value="Schoko">Schoko</option>
        <option value="Frucht">Frucht</option>
    </select>
    <select "id="1Shake">
        <option value="Mix">Mix</option>
        <option value="Schoko">Schoko</option>
        <option value="Vanille">Vanille</option>
    </select>
</div>

var check_attribute = $(this).parents('div.produkt').find('select');
$.each(check_attribute, function (index, value) {
    var name  = $(this).attr('id'),
    wert  = ' ' + $(value).find('option:selected').val();
    attribute = name.substring(1)+wert;
    console.log(attribute);
});

this will output:

Riegel Frucht
Shake Schoko

in console... but i need it in one line, like this:

Riegel Frucht - Shake Schoko

can anybody help me out with this pls?

answered question

FYI, $(value).find('option:selected').val(); can be simplified to just $(value).val() or value.value

2 Answers

7

var line = '';
var check_attribute = $(this).parents('div.produkt').find('select');
$.each(check_attribute, function (index, value) {
      var name = $(this).attr('id'),
      wert = ' ' + $(value).find('option:selected').val();
      attribute = name.substring(1) + wert;
      if(line.lenght>0){
       line += " - ";
      }
      line +=  attribute;
 });
console.log(line);

This server the purpose

posted this
6

You might use .map instead, to get an array of all <select> and selected options strings, and then join those strings by -:

const output = $('select').map(function() {
  return $(this).attr('id').slice(1) + ' ' + $(this).find('option:selected').val();
})
  .get()
  .join(' - ');

console.log(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="auswahl">
  <select id="1Riegel">
    <option value="Mix">Mix</option>
    <option value="Schoko">Schoko</option>
    <option value="Frucht" selected>Frucht</option>
  </select>
  <select id="1Shake ">
    <option value="Mix ">Mix</option>
    <option value="Schoko " selected>Schoko</option>
    <option value="Vanille ">Vanille</option>
  </select>
</div>

Or, you might avoid jQuery entirely, no need to include a big library for something this simple:

const output = Array.prototype.map.call(
  document.querySelectorAll('select'),
  select => select.id.slice(1) + ' ' + select.value
)
  .join(' - ');
  
  
console.log(output);
<div class="auswahl">
  <select id="1Riegel">
    <option value="Mix">Mix</option>
    <option value="Schoko">Schoko</option>
    <option value="Frucht" selected>Frucht</option>
  </select>
  <select id="1Shake ">
    <option value="Mix ">Mix</option>
    <option value="Schoko " selected>Schoko</option>
    <option value="Vanille ">Vanille</option>
  </select>
</div>

posted this

Have an answer?

JD

Please login first before posting an answer.