0

I want to sort the div's that has attribute of "data-letter" alphabetically base on the value of the selected option in the select box. For example if the user select "A" in the select box then each div that has a attribute of "data-letter" will then be arrange alphabetically e.g. "A, B, C, D, E and so on" base in there corresponding "data-letter" attribute content. Any ideas, help, clues, suggestions and recommendations would be greatly appreciated. Thank you!

html structure

<div class="select_holder">
    <select>
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
    </select>
</div>
<div class="box_container">
    <div data-letter="B">
        this is the content of box
    </div>
    <div data-letter="A">
        this is the content of box
    </div>
    <div data-letter="C">
        this is the content of box
    </div>
    <div data-letter="C">
        this is the content of box
    </div>
    <div data-letter="A">
        this is the content of box
    </div>
    <div data-letter="A">
        this is the content of box
    </div>
    <div data-letter="C">
        this is the content of box
    </div>
</div>

my script

$(document).ready(function(){
    $("select").change(function(){
        //$(this).val();
        //I dont know how to make it like sort it up alphatically :(
    });
});
Juliver Galleto
  • 8,831
  • 27
  • 86
  • 164

1 Answers1

0

$(document).ready(function(){
    $("select").change(function(){
        var value = this.options[this.selectedIndex].value;
        var box = $('.box_container');
        box.find('div').sort(function(a,b){
          
          if(a.getAttribute('data-letter') == value){
            return 0;
          }
          if( b.getAttribute('data-letter') == value){
            return 1;
          }
          return (a.getAttribute('data-letter') > b.getAttribute('data-letter')?1:-1);
        }).appendTo(box);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select_holder">
    <select>
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
    </select>
</div>
<div class="box_container">
    <div data-letter="B">
        this is the content of box B
    </div>
    <div data-letter="A">
        this is the content of box A
    </div>
    <div data-letter="C">
        this is the content of box C
    </div>
    <div data-letter="C">
        this is the content of box C
    </div>
    <div data-letter="A">
        this is the content of box A
    </div>
    <div data-letter="Z">
        this is the content of box Z
    </div>
    <div data-letter="A">
        this is the content of box A
    </div>
    <div data-letter="C">
        this is the content of box C
    </div>
      <div data-letter="B">
        this is the content of box B
    </div>
</div>
befzz
  • 1,232
  • 13
  • 11