causita
causita

Reputation: 1708

insert element before another based on attribute value

I create a DIV on the fly and want to position between other Div's it based on their attribute value.

I would like to have it in sequence.

<div data-door="1">1</div>
<div data-door="3">3</div>
<div data-door="4">4</div>
<div data-door="6">6</div>

My code below works but at certain point breaks and the new div starts going out of sequence.

example of out of sequence 1 2 2 3 4 5 4

<input id="txtValue" type="text" > 
<button id="addMe">Add</button>
<div id="container">
    <div data-door="3">3</div>
</div>
$("#addMe").click(function(){
    var strValue = $("#txtValue").val()
    var newDiv = '<div data-door="' + strValue + '">'+ strValue +'</div>'

    //loop thru all divs with data-door
    $('*[data-door]').each(function(){
        console.log($(this).attr("data-door"))
        if ( $(this).attr("data-door") >= strValue ) {

            $(this).prepend(newDiv)
            return false; 
        }
        else{
            $("#container").append(newDiv)
            return false; 
        }

    });

});

Here is the JSFiddle https://jsfiddle.net/czcz/1sg5gyqj/26/

I can't figure why is it going of of sequence

Upvotes: 1

Views: 55

Answers (2)

Martin P.
Martin P.

Reputation: 292

Too complicated:

$("#addMe").click(function(){
	var strValue = $("#txtValue").val();
	var str = '<div data-door="' + strValue + '">'+ strValue +'</div>';
  var wrapper = $('#container');
  $(wrapper).append(str);
  $('div[data-door]').sort(sortIt).appendTo(wrapper);
});
   
function sortIt(a, b){
    return ($(b).data('door')) < ($(a).data('door')) ? 1 : -1;    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="txtValue" type="text" > 
<button id="addMe">Add</button>

<div id="container">

</div>

Upvotes: 2

Alejandro C.
Alejandro C.

Reputation: 3801

You're returning false in both cases in your loop, causing it to break after the first iteration. This works:

$("#addMe").click(function(){
  var strValue = $("#txtValue").val();
  var str = '<div data-door="' + strValue + '">'+ strValue +'</div>';
  if($.trim($("#container").html())==''){ 
    $('#container').append(str);
  } else {
    //loop thru all divs with data-door
    var added = false;

    $('*[data-door]').each(function(){
      console.log($(this).attr("data-door"))
      if ( $(this).attr("data-door") >= strValue ) {
        $(this).prepend('<div data-door="' + strValue + '">'+ strValue +'</div>')
        added = true;
        return false; 
    }});

    if (!added) {
      $("#container").append(str)
    }
  }
});

Upvotes: 1

Related Questions