forX forX - 17 days ago 7
Javascript Question

javascript order by simple hierarchy in page

I got a list of link (error message) pointing to a control into a page.
The order of links is not the same as the control there pointing to.
I want to reorder my links.

sample :



$(function() {
//reorder errorList,
// getOrder(idcontrol){???}
});

input, select,a {
display:table;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3>The original list or errors.</h3>
<div id="errorList">
<a data-idcontrol="textbox2">error textbox2</a>
<a data-idcontrol="list3">error list3</a>
<a data-idcontrol="textbox1">error textbox1</a>
<a data-idcontrol="textbox2">error textbox2</a>
<a data-idcontrol="list1">error list1</a>
</div>

<h3>Elements in the page</h3>
<input type="text" id="textbox1"/>
<input type="text" id="textbox2"/>
<select id="list1"><option>item1</option></select>
<input type="text" id="textbox3"/>
<select id="list2"><option>item1</option></select>
<select id="list3"><option>item1</option></select>


<h3>What should be the list of errors after been reordered.</h3>
<div id="errorListShouldBeAfterReorderOnLoad">
<a data-idcontrol="textbox1">error textbox1</a>
<a data-idcontrol="textbox2">error textbox2</a>
<a data-idcontrol="textbox2">error textbox2</a>
<a data-idcontrol="list1">error list1</a>
<a data-idcontrol="list3">error list3</a>
</div>




Answer

You can sort the errors based on the index of the element it belongs to

$('#errorList a').sort(function(a,b) {
    var data1  = $(a).data('idcontrol'),
        data2  = $(b).data('idcontrol'),
        index1 = $('#' + data1).index(),
        index2 = $('#' + data2).index();

    return index1 - index2;
}).appendTo('#errorList');
Comments