0

Hi does anyone know how to assign a value from a variable?

JQUERY:

for (var dates in date_count) {
   $('.class-date').val(dates).append(`<div class="inner-info"><h4>${dates}</h4><span>${date_count[dates]}</span></div>`);
}

Full Jquery: you can refer to this post from the logic i was trying to achieve here: Jquery matching values

  $("#course-date").each(function() {
    let date = $('.course-date').map((i, e) => $(e).data('value')).toArray();

    let reducer = (a, c) => {
      // If the date doesn't exist 
      a[c] === undefined ?
        a[c] = 1 : // One occurrence, else
        a[c] = a[c] + 1;  // Increment count
      return a;
    }

    let date_count = date.reduce(reducer, {});

    // Create HTML Elements
     var i = 0;
    for (var dates in date_count) {
      $('.class-date').eq(i).val(dates).append(` ${date_count[dates]}`);
      i++;
    }
  });

I am trying to assign it to an option value:

HTML:

<option class="class-date type-filter" value=""></option>
mgonz
  • 45
  • 1
  • 8

1 Answers1

0

You need a variable with the index of the option so you only update one option at a time.

However, this is creating invalid HTML. You can't put other elements inside <option>. See is it possible to add <div> or <span> inside an <option> tag?. In my code below I just append the value without putting it in another element.

var date_count = {
  opt1: "Option 1",
  opt2: "Option 2",
  opt3: "Option 3",
  opt4: "Option 4"
};

var i = 0;
for (var dates in date_count) {
  $('.class-date').eq(i).val(dates).append(` ${date_count[dates]}`);
  i++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
  <option class="class-date">A</option>
  <option class="class-date">B</option>
  <option class="class-date">C</option>
  <option class="class-date">D</option>
</select>
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Hi there, I replaced the code and removed the divs in the append area and it is still not working. I also tried to take out all the h4 and span also and that didnt work. I lastly removed the append all together and that didn't work. – mgonz May 01 '20 at 17:13
  • Thank you but this is my date count: let date_count = date.reduce(reducer, {}); This is my full code: – mgonz May 01 '20 at 18:44
  • It is under: Full Jquery in my original post. – mgonz May 01 '20 at 18:49
  • It doesn't matter where the data comes from. This works with any object. – Barmar May 01 '20 at 18:50
  • Do you already have the ` – Barmar May 01 '20 at 18:51