0

I have multiple selects with the same class name. How can I count the sum of the selected options?

My html/Twig (I have like 6 more selects with the class "adults-select")

<select class="adults-select" data-type="adults">
   {% for i in 1..5 %}
   <option value="{{ i }}">{{ i }}</option>
   {% endfor %}
</select>

My Jquery

$(document).on('change', '.adults-select', function(){
   var sum = 0;
   $("select.adults-select option:selected").each(function(){
      sum += Number($(this).val());
   });
console.log(sum);
});

If I use sum += Number($(this).val()); and I pick 3 adults, I get in 12 in my console.

If I use sum += parseInt($(this).val()); I get Nan in my console

If I use sum += $(this).val(); I get something like 03111111 in my console.

So basically, how can I get the sum of the values I have in my selects?


Added HTML code

<!-- BEGIN common_search_form_hotel -->
<form id="search_hotel_form" action="{{__pages.search_hotel}}" class="container">
  <div class="form-search-table">
    <div id="hotel-search-city-and-name" class="hotel-row-0 d-flex">
      <div class="d-flex mb-3 flex-fill">
        {#<span class="input-icon align-self-center">#}
        {#  <img src="{{__globals.config.paths.upload}}/assets/images/flag.png">#}
        {#</span>#}
        <input class="input_search_in_2 flex-fill shadow-sm" id="hotel_city_name" placeholder="{% filter translate|e %}Choose a city for destination{% endfilter %}" type="text" required />
        <input type="text" id="hotel_city_id" required style="display:none;"/>
      </div>

    </div>
    {#<div class="hotel-row-1">#}



        <input id="hotel-checkin-date" class="input_search_with_title" type="text" required>

        {#<p class="div_title_hotel">{% filter translate %}check-out{% endfilter %}</p>#}
        <input id="hotel-checkout-date" class="input_search_with_title" type="text" required>
      {#</div>#}

<div class="hotel-row-2 template hotel_rooms" id="hotel_room_template">

    <div class="room_people_margin_left d-flex">

        <div class="mb-3 d-block d-md-inline-flex order-2 order-md-1">

          {# makeselectpicker #}

          <div class="titles">
              <p class="div_title_adults">{% filter translate %}Adults{% endfilter %}</p>

              <p class="div_title_children">{% filter translate %}Children{% endfilter %}</p>

              <p class="div_title_child_age1">{% filter translate %}Child 1 Age{% endfilter %}</p>

              <p class="div_title_child_age2">{% filter translate %}Child 2 Age{% endfilter %}</p>
          </div>

          <select class="adults-select" data-above-text="{% filter translate|e %}adults{% endfilter %}" data-type="adults">
              <option value="" disabled >Number of Adults</option>
            {#<optgroup label="{% filter translate|e %}adults{% endfilter %}">#}
              {#{% for i in 1..5 %}#}
              {#<option value="{{ i }}">{{ i }}</option>#}
              {#{% endfor %}#}
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
            {#</optgroup>#}
          </select>

          <select class="children-select" data-above-text="{% filter translate|e %}children{% endfilter %}" data-type="children">
              <option value="" disabled >Number of Children</option>
            {#<optgroup label="{% filter translate|e %}children{% endfilter %}">#}
              {% for i in 0..2 %}
              <option value="{{ i }}">{{ i }}</option>
              {% endfor %}
            {#</optgroup>#}
          </select>

          <select class="child-age-select-1" data-above-text="{% filter translate|e %}age child 1{% endfilter %}" data-type="child_1_age" >
            {#<optgroup label="{% filter translate|e %}age child 1{% endfilter %}">#}
            <option value="" disabled >Child 1 Age</option>
              {% for i in 0..17 %}
              <option value="{{ i }}">{{ i == 0 ? ("&lt;1y"|translate) : ( i == 1 ? ('1y'|translate) : ('%dy'|translate|format(i))) }}</option>
              {% endfor %}
            {#</optgroup>#}
          </select>

            {# child-age-select2 #}
          <select class="child-age-select-2 " data-above-text="{% filter translate|e %}age child 2{% endfilter %}" data-type="child_2_age">
              <option value="" disabled >Child 2 Age</option>
            {#<optgroup label="{% filter translate|e %}age child 2{% endfilter %}">#}
              {#<optgroup label="{% filter translate|e %}age child 1{% endfilter %}">#}
              {% for i in 0..17 %}
              <option value="{{ i }}">{{ i == 0 ? ("&lt;1y"|translate) : ( i == 1 ? ('1y'|translate) : ('%dy'|translate|format(i))) }}</option>
              {% endfor %}
            {#</optgroup>#}
          </select>
        </div>


        <div class="">
            <p class="div_title_hotel">{% filter translate %}Rooms{% endfilter %}</p>

          {#<span class="input-icon align-self-center">#}
          {#  <img src="{{__globals.config.paths.upload}}/assets/images/bed.png" class="">#}
          {#</span>#}

        <select class="rooms-select shadow-sm" required data-type="rooms">
            <option value="" disabled selected="selected" >Number of Rooms</option>
            {#<optgroup label="{% filter translate %}rooms{% endfilter %}">#}
              {% for i in 1..5 %}
              <option value="{{ i }}">{{ i }}</option>
              {% endfor %}
            {#</optgroup>#}
          </select>
            <input type="text" class="col-6 shadow-sm input_search_with_title" name="datefilterhotel" readonly="readonly" placeholder="Pick your Dates" value="" style="font-size:0.8em" />
        </div>
      </div>
    </div>
    <input class="input_search_in_2 flex-fill" id="hotel_name" placeholder="{% filter translate|e %}hotel name{% endfilter %} ({% filter translate|e %}optional{% endfilter %})" type="text" required/>
          {#<span class="input-html-placeholder"><span class="input-html-placeholder-content">{% filter translate %}hotel's name{% endfilter %} <em>({% filter translate %}optional{% endfilter %})</em></span></span>#}
  </div>

  <a id="hotel_search_button" href="javascript:void(0);">
    <p class="search_big_but search_hotel">{% filter translate %}Find your best accommodation{% endfilter %}</p>
  </a>
  <input type="submit" style="display:none" />
</form>
<!-- END common_search_form_hotel -->

3 Answers 3

1

Try this: You are using .val() but jquery selector is options instead of select element. Also, for extra check you can return 0 if parseInt fails

$(document).on('change', '.adults-select', function(){
   var sum = 0;
   $("select.adults-select").each(function(){
      sum = parseInt(sum) + (parseInt($(this).val()) || 0);
   });
console.log(sum);
});
Sign up to request clarification or add additional context in comments.

5 Comments

Same thing :/ When I pick 1 Adult, I get 10 in my console. When I pick 2 Adults, I get 11 in my console. When I pick 4 Adults, I get 13 in my console.
try updated post, in your case somehow sum is considered as text instead of number hence instead of adding number it is concatenating the values
I tried the Updated code. It's still giving me the same thing.
I technically can, But I using Twig and I doubt it is going to be useful as I am using and importing multiple snippets :/
I would suggest to do debugging on the browser which way you can find what exactly happening on the js code. You can check stackoverflow.com/questions/66420/… or google if using different browser
0

Your code is just ok. just add condition before += to check getting value or '' option selected.

$(document).on('change', '.adults-select', function(){
   var sum = 0;
   $("select.adults-select option:selected").each(function(){
      if($(this).val()){
        sum += Number($(this).val());
      }
      
   });
console.log(sum);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="adults-select" data-type="adults">
  <option value=""></option>
   <option value="5">5</option>
   <option value="6">6</option>
   
</select>

<select class="adults-select" data-type="adults">
  
   <option value="8">8</option>
   <option value="9">9</option>
   
</select>

4 Comments

Same thing :/ When I pick 1 Adult, I get 10 in my console. When I pick 2 Adults, I get 11 in my console. When I pick 4 Adults, I get 13 in my console.
post your all select html here.
I think your select is the problem too, if you share the generated HTML it's a lot easier to debug
I added the HTML code, but I don't know if it is going to be of much help
0

Here's a vanilla JS example of what I think you're trying to do.

var adSels = document.querySelectorAll('.adults-select');

var val = null;

adSels.forEach(function(adSel) {
  adSel.addEventListener('change', function() {
    val = 0
    adSels.forEach(function(adSel) {
      val += Number(adSel.value);
    });
    console.log(val);
  });
});
<select class="adults-select" data-type="adults">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

<select class="adults-select" data-type="adults">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

5 Comments

I get Nan with this :(
Sorry, I broke it trying to remove all the ES6, fixed now!
You're gonna hate me for this. But, I am still getting Nan.
Are you getting NaN in the browser example or in your code? If it's here it might be a cross-browser compatibility issue, if it's in your code you might be adding something that can't be parsed as a number. For example Number('a string') // => NaN
It's in the browser

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.