sqarf sqarf - 4 months ago 13
Javascript Question

Jquery from one range get one value, from other range get second value, from other range get third value etc

Consider this code example:

HTML

<div class="number_group">
<span class="min">0</span> -
<span class="max">5</span>:
<span class="value">10</span>
</div>

<div class="number_group">
<span class="min">6</span> -
<span class="max">10</span>:
<span class="value">16</span>
</div>

<div class="number_group">
<span class="min">11</span> -
<span class="max">15</span>;
<span class="value">20</span>
</div>

<div class="number_group">
<span class="min">16</span> -
<span class="max">20</span>;
<span class="value">22</span>
</div>

<label>
<input type="number" id="input_val" min="0" max="20" />
<button id="check" type="button">Check</button>
</label>


What i want to achive with jquery is, after user enters number in $('input#input_val') and clicks on $('button#check') function returns value in given range.

For example, if user enters number 3, function will return "10";

For example, if user enters number 8, function will return "16", etc

The list shold be dynamic, meaning we don't know how many $('div.number_group') ar given.

I'm really stuck on this one and I don't know where to even begin.

Answer

Iterate over .number_group and find out the value based on min and max.

$('#check').click(function() {
  var res,
    // get the entered value  
    num = +$('#input_val').val();
  // iterate over the divs
  $('.number_group').each(function() {
    // check the value within min and max
    if (num >= +$('.min', this).text() && num <= +$('.max', this).text()) {
      // if within range set the result as its value
      res = +$('.value', this).text();
      // break the loop by returning false, since we are findout our value
      return false;
    }
  })
  console.log(res);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="number_group">
  <span class="min">0</span> -
  <span class="max">5</span>:
  <span class="value">10</span>
</div>

<div class="number_group">
  <span class="min">6</span> -
  <span class="max">10</span>:
  <span class="value">16</span>
</div>

<div class="number_group">
  <span class="min">11</span> -
  <span class="max">15</span>;
  <span class="value">20</span>
</div>

<div class="number_group">
  <span class="min">16</span> -
  <span class="max">20</span>;
  <span class="value">22</span>
</div>

<label>
  <input type="number" id="input_val" min="0" max="20" />
  <button id="check" type="button">Check</button>
</label>

Comments