Reputation: 41
I have few inputs, and it comes with values from 1 to 100 in it, but user can alter those values. I have sorted my inputs in Ascending order. Now I want that each time user changes an input, they should be re-arranged in ascending order. Here is my HTML template:
var sortedArray = $("div[class^='wrap_']").get().sort(function(a, b) {
var idx = parseInt($(a).find(".sort_by").val(),10);
var idx2 = parseInt($(b).find(".sort_by").val(),10);
return idx > idx2;
});
$(sortedArray).appendTo("body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="wrap_0">
<input class="sort_by" value="10"/>
</div>
<div class="wrap_1">
<input class="sort_by" value="3"/>
</div>
<div class="wrap_2">
<input class="sort_by" value="7"/>
</div>
Right now they appear as: 3 7 10 if user changes 3 to 12, I want my output to be automatically changed to: 7 10 12. I want Jquery solutions only. Thanks in advance.
Upvotes: 1
Views: 134
Reputation: 24638
You can use the input
event and apply the sort
method on the parent div
jQuery collection. Please note that I added class wrap
so the divs can be easily selected. The code .trigger('input')
ensures that the input
(actually parent div
) elements are sorted when the page loads.
$(function() {
$('.sort_by').on('focusout', function() {
var arr = $('div.wrap');
arr = arr.sort(function(a,b) {
return +$(a).find('.sort_by').val() - +$(b).find('.sort_by').val();
});
$('body').append( arr );
})
.trigger('focusout');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap_0 wrap">
<input class="sort_by" value="10"/>
</div>
<div class="wrap_1 wrap">
<input class="sort_by" value="3"/>
</div>
<div class="wrap_2 wrap">
<input class="sort_by" value="7"/>
</div>
Upvotes: 0
Reputation: 804
$(document).ready(function(){
sort();
$(".sort_by").change(function(){
sort();
});
function sort(){
var sortedArray = $("div[class^='wrap_']").get().sort(function(a, b) {
var idx = parseInt($(a).find(".sort_by").val(),10);
var idx2 = parseInt($(b).find(".sort_by").val(),10);
return idx > idx2;
});
console.log(sortedArray);
$(sortedArray).appendTo("body");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="wrap_0">
<input class="sort_by" value="10"/>
</div>
<div class="wrap_1">
<input class="sort_by" value="3"/>
</div>
<div class="wrap_2">
<input class="sort_by" value="7"/>
</div>
There...you change a value and press enter...your sort code is executed.
Upvotes: 1