Sorting by cost

I am currently attempting to filter my product list using jQuery based on price (low/high). I have managed to implement this functionality successfully. However, I am facing an issue where clicking the filter causes my products to lose their formatting and ignore their bootstrap classes. I'm unsure why this is happening.

Here is an example of the code:

If you click the link below, you will see the problem in action. Any suggestions or ideas on how to resolve this?

var ascending = false;

$('.tab-content').on('click', '.sortByPrice', function() {

  var sorted = $('.results-row').sort(function(a, b) {
    return (ascending == 
      (convertToNumber($(a).find('.price').html()) <
        convertToNumber($(b).find('.price').html()))) ? 1 : -1;
  });
  ascending = ascending ? false : true;

  $('.results').html(sorted);
});

var convertToNumber = function(value) {
  return parseFloat(value.replace('$', ''));
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

<div class="tab-content">
  <div id="filters">
    <p>
      <a class="sortByPrice" href="#">Sort by Price</a>
    </p>
  </div>
</div>

<div class="results">
...
...
</div>
<!--container.//-->

Answer №1

After reviewing your code, I noticed that the selectors you used were incorrect and you removed two necessary divs for Bootstrap: .container-fluid and .row-mb-4.

To make it less confusing, I changed the selector names to .product for the source and .results for the result div with Bootstrap class.

var ascending = false;

$('.tab-content').on('click', '.sortByPrice', function() {

  var sorted = $('.product').sort(function(a, b) {
    return (ascending ==
      (convertToNumber($(a).find('.price').html()) <
        convertToNumber($(b).find('.price').html()))) ? 1 : -1;
  });
  ascending = ascending ? false : true;

  $('.results').html(sorted);
});

var convertToNumber = function(value) {
  return parseFloat(value.replace('$', ''));
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

<div class="tab-content">
  <div id="filters">
    <p>
      <a class="sortByPrice" href="#">Sort by Price</a>
    </p>
  </div>
</div>

<div>
  <div class="container-fluid">
    <div class="row mb-4 results">
      <div class="col-md-3 product">
        <div>
          <figure class="card card-product">
            <div class="img-wrap item"><img src="http://kb4images.com/Random-Image/number-148116.html">
            </div>
            <figcaption class="info-wrap">
              <h4 class="title">Good product</h4>
              <p class="desc">Some small description goes here</p>
            </figcaption>
            <div class="bottom-wrap">
              <a href="" class="btn btn-sm btn-primary float-right">Order Now</a>
              <div class="price-wrap h5">
                <span class="price-new price">$1280</span> <del class="price-old">$1980</del>
              </div>
              <!-- price-wrap.// -->
            </div>
            <!-- bottom-wrap.// -->
          </figure>
        </div>
        <!-- col // -->
      </div>
      <div class="col-md-3 product">
        <div>
          <figure class="card card-product">
            <div class="img-wrap item"><img src="http://kb4images.com/Random-Image/number-148116.html">
            </div>
            <figcaption class="info-wrap">
              <h4 class="title">Good product</h4>
              <p class="desc">Some small description goes here</p>
            </figcaption>
            <div class="bottom-wrap">
              <a href="" class="btn btn-sm btn-primary float-right">Order Now</a>
              <div class="price-wrap h5">
                <span class="price-new price">$1080</span> <del class="price-old">$1980</del>
              </div>
              <!-- price-wrap.// -->
            </div>
            <!-- bottom-wrap.// -->
          </figure>
        </div>
      </div>
      <!-- col // -->
    </div>
    <!-- row.// -->
  </div>
</div>
<!--container.//-->

Answer №2

Make this change

$('.results-row').sort(function(a, b)

to

$('.col-md-3').sort(function(a, b)

As you are sorting results-row, it appears that you are removing the parent div col-md-3 which has some associated CSS styles.

var ascending = false;

$('.tab-content').on('click', '.sortByPrice', function() {

  var sorted = $('.col-md-3').sort(function(a, b) {
    return (ascending == 
      (convertToNumber($(a).find('.price').html()) <
        convertToNumber($(b).find('.price').html()))) ? 1 : -1;
  });
  ascending = ascending ? false : true;

  $('.results').html(sorted);
});

var convertToNumber = function(value) {
  return parseFloat(value.replace('$', ''));
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

<div class="tab-content">
  <div id="filters">
    <p>
      <a class="sortByPrice" href="#">Sort by Price</a>
    </p>
  </div>
</div>

<div class="results">
  <div class="container-fluid">
    <div class="row mb-4">
      <div class="col-md-3">
        <div class="results-row">
          <figure class="card card-product">
            <div class="img-wrap item"><img src="http://kb4images.com/Random-Image/number-148116.html">
            </div>
            <figcaption class="info-wrap">
              <h4 class="title">Good product</h4>
              <p class="desc">Some small description goes here</p>
            </figcaption>
            <div class="bottom-wrap">
              <a href="" class="btn btn-sm btn-primary float-right">Order Now</a>
              <div class="price-wrap h5">
                <span class="price-new price">$1280</span> <del class="price-old">$1980</del>
              </div>
              <!-- price-wrap.// -->
            </div>
            <!-- bottom-wrap.// -->
          </figure>
        </div>
        <!-- col // -->
      </div>
      <div class="col-md-3">
        <div class="results-row">
          <figure class="card card-product">
            <div class="img-wrap item"><img src="http://kb4images.com/Random-Image/number-148116.html">
            </div>
            <figcaption class="info-wrap">
              <h4 class="title">Good product</h4>
              <p class="desc">Some small description goes here</p>
            </figcaption>
            <div class="bottom-wrap">
              <a href="" class="btn btn-sm btn-primary float-right">Order Now</a>
              <div class="price-wrap h5">
                <span class="price-new price">$1080</span> <del class="price-old">$1980</del>
              </div>
              <!-- price-wrap.// -->
            </div>
            <!-- bottom-wrap.// -->
          </figure>
        </div>
      </div>
      <!-- col // -->
    </div>
    <!-- row.// -->
  </div>
</div>
<!--container.//-->

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Disabling the scrollbar in Selenium screenshots

When using Chromedriver to capture screenshots of webpages, my code effectively does the job. However, I am now facing an issue with removing the unsightly scrollbars from the image. Is it feasible to inject CSS into the webpage in order to achieve this? W ...

Ant Design - Select - Automatically close dropdown when no data is available

I attempted setting notFoundContent to undefined, however it did not resolve the issue. Are there any other possible solutions for this problem? ...

Adding a component to a slot in Vue.js 3

My Goal I aim to pass the Component into the designated slot. The Inquiry How can I effectively pass the Component into the slot for proper rendering? It works well with strings or plain HTML inputs. Additional Query If direct passing is not feasible, ...

ReactJS library encounters "Failed to load PDF file." error intermittently while attempting to view a PDF file

I recently developed a React JS application using create-react-app and decided to incorporate react-pdf for viewing PDF files. However, I've encountered an intermittent issue where the PDF sometimes fails to load. Specifically, when I initially load t ...

Guide to emitting a value using the composition API

I'm currently working with a datepicker component that is part of a form in my Vue3 app using the composition API. My challenge is how to pass a value from the datepicker component back up to the form component. Unfortunately, I've encountered ...

Challenge in WordPress Development

As a beginner in website building, I am looking to customize the background of my pages with a solid color. The current SKT Full Width theme I am using has an opaque background which is causing the text on my slider to blend in and not look appealing. All ...

What mistakes am I making in including/injecting functions in AngularJS controllers and factories?

I'm encountering an issue in Angular where I am struggling to inject my factory into my controller. The error message I'm receiving is "Cannot read property 'validar' of undefined". In my project, I have two files - ServiceUtil.js which ...

I possess a pair of UI tabs. Whenever a button located outside the tab is clicked, I am required to activate a distinct tab

As a beginner in Javascript, I recently encountered an issue with a UI tab element that contains two tabs. My goal is to create a button that, when clicked, will scroll up and activate the second tab. <style> .tab-container { overflow-x: ...

I'm looking to showcase the list in a navigation bar by clicking on the hamburger menu. I want to include the 'home' and 'about' text specifically

Having trouble implementing the hamburger menu functionality in my HTML/CSS project. When clicked on a shrunken screen, I want the 'Home' and 'About' text in the nav to appear stacked on top of each other. JS is causing me some difficul ...

I can't seem to understand why the error "bash: ng: command not found" keeps popping up even though I

Ever since I installed Angular CLI and started working with Angular, something strange happened - the ng command suddenly became not found: ng serve -o Here's a screenshot for reference: bash: ng: command not found Oddly enough, when I use the npx c ...

Error Message: ElectronJS - Attempted to access the 'join' property of an undefined variable

I am currently working on developing a tray-based application. However, I am encountering an error that reads: Uncaught TypeError: Cannot read property 'join' of undefined Can anyone guide me on how to resolve this issue? This is the content ...

Tips on retrieving an input value from a dynamic list

I am struggling to retrieve the correct value with JavaScript as it always shows me the first input value. Any help would be greatly appreciated! Thank you in advance! <html> <head> </head> <body> <?php while($i < $forid){ ...

Animated collapse with margin effect in Material-UI

I have been utilizing the MUI-Collapse component to display collapsible content within a list. I am looking to add vertical spacing between the Collapse components in the list, but I do not want the spacing to remain when the Collapse is collapsed. I am ha ...

What is the CSS technique for displaying text overflow after displaying only two lines within a div?

Currently working on a webpage design where I am looking to display text overflow using ellipsis within a div. However, my requirement is to display two lines of data in the div before handling the text overflow. I prefer not setting a fixed height for t ...

Creating dirty or touched input programmatically in Angular2 can be achieved by using the `.markAsT

Looking to integrate a JQuery plugin with Angular2? Essentially, this plugin generates a duplicate of specific HTML content containing inputs. As data is modified, Angular2 automatically re-renders the content along with any errors. However, the challenge ...

Error: Attempting to destructure without initializing / identifier 'name' is already in use [mysql][nodejs]

Whenever I attempt to pass keys as parameters, I'm encountering these errors in nodemon: SyntaxError: Identifier 'name' has already been declared This is the model function causing the issue: const create = async (name, about, site) => { ...

Remove the default CSS styling from Django CMS

When using Django CMS' text plug-in, I've noticed that the text is hardcoded with its own CSS, specifically within the p tags. Is there a way to remove this default styling? I would like for the text to inherit the styles defined in the theme I a ...

"Troubleshooting: Issue with Material-UI TextField not

Currently working with version "@material-ui/core": "^4.2.1" of material-ui. The following code snippet is not matching the examples provided on the website: <div> <TextField id="outlined-search" label="Search field" type="search" variant="ou ...

Having trouble parsing an array of JSON objects

My brain is struggling to understand how to handle JSON objects properly. Below is the JavaScript code causing me stress: function get_cities(id) { $('#def').hide(); $('#cities').html(''); $.get('/emprego/i ...

Utilizing libraries in JavaScript

For a while now, I've been grappling with an issue related to importing modules into my main JavaScript script. I recently installed the lodash library via npm and I'm trying to import it into my main script so that I can utilize its functionali ...