Home > front end >  Sort Select box by price with jQuery
Sort Select box by price with jQuery

Time:01-10

I want the options to be sorted by price. I tried different codes but I was not successful!

This is my normal box:

 <select id="product-list">
 <option>product 1- [2$]</option>
  <option>product 2- [4$]</option>
    <option>product 3- [0.5$]</option>
    <option>product 4- [1.5$]</option>
    </select>

But I mean something like this:

 <select id="product-list">
 <option>product 3- [0.5$]</option>
  <option>product 4- [1.5$]</option>
    <option>product 1- [2$]</option>
    <option>product 2- [4$]</option>
    </select>

How can this be done with jQuery?

CodePudding user response:

Not trivial

const re = /\[(\d \.?\d*)\$\]/; // matches an amount
const opts = $("#product-list").find("option"); // get the options
opts.sort(function(a,b) {  // sort them using the textContent 
  const a_amt = a.textContent.match(re)[1];
  const b_amt = b.textContent.match(re)[1];
  return a_amt-b_amt;
})
$("#product-list").html(opts); // re-insert the sorted options
$("#product-list")[0].selectedIndex = 0; // select the new first option
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<select id="product-list">
  <option>product 1- [2$]</option>
  <option>product 2- [4$]</option>
  <option>product 3- [0.5$]</option>
  <option>product 4- [1.5$]</option>
</select>

  •  Tags:  
  • Related