jQuery dynamic number comparison

Issue

I have a form with 1 input and 1 select with options (example: 2500, 3000, 4000, 5000)

I need to be able to:

  • Create an array for each options in the select
  • When I enter a value in the input field (number)
  • Determine between each select.value is the text.value
  • Fake click on the select.value which is the "min" range.

Example :

  • input = 2800 > Fake click on selection.option(2500)
  • input = 3200 > Fake click on selection.option(3000)

Where it’s tricky, that’s the select has different value on each page.

At this time, to test:

<input min="0" max="7000" class="largeur" value="" type="number" placeholder="" required="">

<select id="longueur" class="" name="attribute_longueur" data-attribute_name="attribute_longueur" data-show_option_none="yes">
  <option value="">Choisir une option</option>
  <option value="2508" class="attached enabled">2508</option>
  <option value="4785" class="attached enabled">4785</option>
</select>
$(".largeur").keyup(function() {
  console.log('keyup');
  $('#longueur option[value="2508"]').prop('selected', true); // Only to test fake click on value 2508
});

Thanks for the help!

Solution

To create the array of values you can use map(). From there you simply need to read the value which is typed in to the number input, then determine which value in the array is closest to that. The latter can be done following the code provided by @JoeGrund in this excellent answer. Then it’s just a matter of setting the val() of the select. Try this:

var $select = $('#longueur');
var values = $select.children('option').map(function() {
  var value = $(this).val();
  return value.trim() == '' ? null : parseInt($(this).val(), 10);
}).get();

$('.largeur').on('input', function() {
  var typedValue = parseInt($(this).val(), 10);
  var closestValue = values.reduce(function(prev, curr) {
    return (Math.abs(curr - typedValue ) < Math.abs(prev - typedValue ) ? curr : prev);
  });
  $select.val(closestValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input min="0" max="7000" class="largeur" value="" type="number" placeholder="" required="">

<select id="longueur" class="" name="attribute_longueur" data-attribute_name="attribute_longueur" data-show_option_none="yes">
  <option value="">Choisir une option</option>
  <option value="2508" class="attached enabled">2508</option>
  <option value="4785" class="attached enabled">4785</option>
</select>

Answered By – Rory McCrossan

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.