Sorting disrupts the changing of nr - javascript

I have a problem with the sorting of a Javascript list. The list that is created when a text area is filled and a grading is chosen. It looks like this:
var element = '<li class="lista">' + filmen + '<span class="betyg">' + changeNumber(grade) + '</span></li>';
film_list.append(element);
I also have a function that converts the number in the span element to stars, it looks like this:
function changeNumber(number) {
var stars = "";
for(var i = 0; i < number; i++) {
stars += "*";
}
return stars;
}
The problem is that there are two buttons to sort the list, high and low depending on the grade, and when I push the buttons the list is sorted correctly. However, the stars disappear and the numbers turn up again. I have tried to call the function changeNumber from the sorting button but it doesn't seem to work. I'm not sure what I should use as the argument. Any suggestions as to what I should do?
The sorting function looks like this:
var button_high = $('#high');
var betyg_array = new Array();
button_high.click(function () {
$list = $("#filmerna ul");
$("#filmerna ul li")
.remove();
betyg_array.sort(function (x, y) {
return y[1] - x[1]
});
$.each(betyg_array, function () {
$nyFilm = $("<li />");
$nyFilm.attr("class", "lista")
$nyFilm.text($(this)[0]);
$nyBetyg = $("<span />");
$nyBetyg.attr("class", "betyg");
$nyBetyg.text($(this)[1]);
$nyBetyg.appendTo($nyFilm);
$nyFilm.appendTo($list);
changeNumber();
});
});

var button_high = $('#high');
var betyg_array = new Array();
button_high.click(function () {
$list = $("#filmerna ul");
$("#filmerna ul li")
.remove();
betyg_array.sort(function (x, y) {
return y[1] - x[1]
});
$.each(betyg_array, function () {
$nyFilm = $("<li />");
$nyFilm.attr("class", "lista")
$nyFilm.text($(this)[0]);
$nyBetyg = $("<span />");
$nyBetyg.attr("class", "betyg");
$nyBetyg.text($(this)[1]);
var stars = $nyBetyg.text(betyg_array); //this line and the line below was the solution
$nyBetyg.text(changeNumber(stars));
$nyBetyg.appendTo($nyFilm);
$nyFilm.appendTo($list);
});
});

Related

Nesting a function returning NaN

I am running into an error when I try nesting a simple counter function inside an existing function. I know some people frown upon this, so if there is any other way of doing this, it would be greatly appreciated. Basically, I am calling a function to parse a JSON string to get 3 numbers. I would like to animate those 3 numbers with a counter every time a new calculation is made. My instinct is to place this counter function inside of the same for loop that runs to get the numbers themselves. Doing so returns NaN. I'm sure there is something very little that I am missing here that I am hoping someone can pick up on.
Code:
var text = '{JSON data}'
var obj = JSON.parse(text);
function calculate() {
var e = document.getElementById("ltSpecialtyList");
var selectedSpec = e.options[e.selectedIndex].text;
console.log(selectedSpec);
var x = document.getElementById("ltLocationList");
var selectedState = x.options[x.selectedIndex].text;
console.log(selectedState);
for (i = 0; i < obj.values.length; i++)
{
if (obj.values[i].State == selectedState && obj.values[i].Specialty == selectedSpec)
{
// DISPLAY RESULTS DIV (JQUERY)
var $resultsDiv = $("#ROI-results");
$resultsDiv.fadeIn();
// CAPTURE HEADER SPAN NAMES
var headerState = document.getElementById("header-state-name");
var headerSpec = document.getElementById("header-specialty-name");
// CLEAR STATE AND SPECIALTY FROM SPAN
headerState.innerHTML = "";
headerSpec.innerHTML = "";
// ADD SELECTED STATE AND SPECIALTY
headerState.innerHTML += selectedState;
headerSpec.innerHTML += selectedSpec;
// CAPTURE RESULT DATA DIVS
var permResults = document.getElementById("ROI-results-perm-data");
var locumResults = document.getElementById("ROI-results-locums-data");
var uncollectedResults = document.getElementById("ROI-results-uncollected-data");
// CLEAR DATA DIVS
permResults.innerHTML = "";
locumResults.innerHTML = "";
uncollectedResults.innerHTML = "";
//POPULATE DIV WITH DATA
permResults.innerHTML += "<p class='ROI-results-data-number univers-bold'>" + obj.values[i].Permanent + "</p>";
locumResults.innerHTML += "<p class='ROI-results-data-number univers-bold'>" + obj.values[i].Locums + "</p>";
uncollectedResults.innerHTML += "<p class='ROI-results-data-number univers-bold'>" + obj.values[i].Gross + "</p>";
}
// COUNTER
$('.ROI-results-data-number').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
}
}

How can I show only the row of a table that has the same value that was entered in a textbox with jquery

I have a table of rank where I type the ID of the rank and it shows me only the column line that has this line as my code:
$('button').click(function () {
var data = $("textarea").val();
var rank = $("#rank").val();
if(rank == ""){
alert("digit rank number");
}
else{
data = data.replace(/\s/, " #");
data = data.replace(/([0-9]\s)/g, "$1#");
var lines = data.split("#"),
output = [],
i;
for (i = 0; i < lines.length; i++)
output.push("<tr><td>" + lines[i].slice(0,-1).split(",").join("</td><td>") + "</td></tr>");
output = "<table>" + output.join("") + "</table>";
var valuefinal = $(output).find('tr').filter(function(){
return $(this).children('td').eq(1).text() == rank;
});
$('#fileDisplayArea').html(valuefinal);
}
});
I'm doing this filter in that part of the code
var valuefinal = $(output).find('tr').filter(function(){
return $(this).children('td').eq(1).text() == rank;
});
$('#fileDisplayArea').html(valuefinal);
DEMO CODE
(Forgive me if you did not understand something, my english sucks. I hope it is clear what I need.)
You need to change this -
return $(this).children('td').eq(1).text() == rank;
to this -
return $(this).children('td').eq(0).text() == rank;
.eq() is a zero-based array method.
http://jsfiddle.net/jayblanchard/qM6Fj/19/
http://api.jquery.com/eq/
You need to have a search feature for the contents you have displayed in the table is what i got.....
You can use jQuery DataTable for this purpose which does this job link .. scroll down to see the table show with sort, search etc features

Sorting dynamic table in jquery

Sorry but I'm completly new to js and jquery.
I got dynamic table which values are in localstorage. I can add new row, delete row, and edit cells. This is working.
I want to add a sorting this table by clicked colum. I found here code and try it. It just working when I write table and not use my javascript to add rows from localstorage. Table in two cases looks same in html code. I have no idead why sorting isnt working with dynamic table.
This is w/o my dynamic table from localstore, sorting as supposed to:
http://jsfiddle.net/eW8Kg/1/
This is with table from localstorage(not working in jsfiddle?) on my comupter this is working good, but table is not sorting! (I left this static values):
http://jsfiddle.net/XAu5G/
I think my problem can be in creation of table content:
var Html = "<tbody>";
for (var i = 1; i < localStorage.length; i++) {
var input = "<td><input style='border:hidden' class=\"fields\" name = " + localStorage.key(i) + " type='text' onchange='change(\"" + localStorage.key(i) + "\")' /></td>"
Html += "<tr class=\"field\">";
for (var j = 0; j < 4; ++j) {
Html += input;
}
var button = "<td><input type='button' value = 'UsuĊ„' onclick='Remove(\"" + localStorage.key(i) + "\")'></td>";
Html += button + "</tr>";
}
Html += "<tr id=\"actions\"></tr></tbody>"
document.getElementById("list").innerHTML += Html;
This jquery code do sorting:
$(document).ready(function() {
var table = $('#list');
jQuery.fn.sortElements = (function() {
var sort = [].sort;
return function(comparator, getSortable) {
getSortable = getSortable || function() {return this;};
var placements = this.map(function() {
var sortElement = getSortable.call(this),
parentNode = sortElement.parentNode,
// Since the element itself will change position, we have
// to have some way of storing it's original position in
// the DOM. The easiest way is to have a 'flag' node:
nextSibling = parentNode.insertBefore(
document.createTextNode(''),
sortElement.nextSibling
);
return function() {
if (parentNode === this) {
throw new Error(
"You can't sort elements if any one is a descendant of another."
);
}
// Insert before flag:
parentNode.insertBefore(this, nextSibling);
// Remove flag:
parentNode.removeChild(nextSibling);
};
});
return sort.call(this, comparator).each(function(i) {
placements[i].call(getSortable.call(this));
});
};
})();
$('#x').click(function(){
$('#list').hide();
});
$('#nazwa-header').wrapInner('<span title="sort this column"/>').each(function() {
var th = $(this),
thIndex = th.index(),
inverse = false;
th.on('click', function() {
table.find('td').filter(function() {
return $(this).index() === thIndex;
}).sortElements(function(a, b) {
console.log($(a).find('input').val(),$(b).find('input').val());
return $(a).find('input').val() > $(b).find('input').val() ?
inverse ? -1 : 1
: inverse ? 1 : -1;
}, function() {
// parentNode is the element we want to move
return this.parentNode;
});
inverse = !inverse;
});
});
});

Using values from Array to execute function in jQuery

I have a page that contains several divs. The divs have the same postfixes but different prefixes. What I want to do is loop through them and if one of them contain a 0 hide the description div.
The divs look like this:
<div id="first_desc">First</div><div id="first_note1">0</div>
<div id="second_desc">Second</div><div id="second_note1"></div>
<div id="third_desc">Third</div><div id="third_note1"></div>
My script is this:
$(document).ready(function() {
// Variables
var firstdiv = 'first';
var seconddiv = 'second';
var thirddiv = 'third';
// Array
var myArray = new Array(firstdiv, seconddiv, thirddiv);
for(var x = 0; x < myArray.length; x++) {
if('$("#' + myArray[x] + '_note1").text() === $.trim("0")') {
'$("#' + myArray[x] + '_desc").hide()';
}
}
});
So far this code is not working. Can anyone help me? Thanks.
You have some extra ' in there.
if($("#" + myArray[x] + "_note1").text() === $.trim("0")) {
$("#" + myArray[x] + "_desc").hide();

How to sort a random div order in jQuery?

On page load, I am randomizing the order of the children divs with this Code:
function reorder() {
var grp = $("#team-posts").children();
var cnt = grp.length;
var temp, x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$("#team-posts").append($(grp));
}
I cannot seem to figure out how to get the posts back in the original order. Here's the demo of my current code http://jsfiddle.net/JsJs2/
Keep original copy like following before calling reorder() function and use that for reorder later.
var orig = $("#team-posts").children();
$("#undo").click(function() {
orderPosts();
});
function orderPosts() {
$("#team-posts").html( orig ) ;
}
Working demo
Full Code
var orig = $("#team-posts").children(); ///caching original
reorder();
$("#undo").click(function(e) {
e.preventDefault();
orderPosts();
});
function reorder() {
var grp = $("#team-posts").children();
var cnt = grp.length;
var temp, x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$("#team-posts").append($(grp));
}
function orderPosts() {
// set original order
$("#team-posts").html(orig);
}
How about an "undo" plugin, assuming it applies?
Just give each item a class with the corresponding order and then get the class name of each div and save it to a variable
$("#team-posts div").each(function() {
var parseIntedClassname = parseInt($(this).attr("class");
arrayName[parseIntedClassname] = $("#team-posts div." + parseIntedClassname).html()
});
You can reorder them from there by saving their html to an array in order
$("#team-posts").html();
for(var i=0;i<arrayName.length;i++){
$("#team-posts").append('<div class="'+i+'">'+arrayName[i]+'</div>');
}
The solution with saving away the original order is probably the best but if you have to dynamically sort it, you can use this:
http://www.w3schools.com/jsref/jsref_sort.asp
function orderPosts() {
var $grp = $("#team-posts"),
ordered = $grp.children().toArray().sort(function(a, b) {
return parseInt($(a).text()) > parseInt($(b).text());
});
$grp.empty().append(ordered);
}

Categories

Resources