javascript slider gets reset if I navigate to the second page - javascript

I have a javascript function which dynamically updates the page content based on the UI slider values that I am selecting. This is the javascript function.
<script>
var masterData=[];
$(function() {
$("button").on('click',function(){ loadXMLDoc(); });
$("[data-slider]")
.each(function (index) {
var range;
var input = $(this);
$("<span>").addClass("output").attr("id","output"+index)
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.on("slider:ready slider:changed", function (event, data) {
var $output =$(this).nextAll(".output:first");
$output.html(data.value.toFixed(2));
masterData[$output.attr("id").replace(/output/,"")] = data.value;
$("#kwBody > tr").each(function() {
var $cells = $(this).children("td");
var found=false,count=0,currentCell;
for (var i=0;i<masterData.length;i++) {
currentCell=$cells.eq(i+1);
found = parseInt(currentCell.text(),10) >=masterData[i];
currentCell.toggleClass("found",found); //add or remove class to highlight
count+=found;
}
window.console && console.log(masterData,count);
$(this).toggle(count==masterData.length); // show if all cells >
});
});
});
</script>
However, the problem is if I navigate to the second page, the slider gets reset. Also, the function selects the values based on the UI slider only for the page that am currently in. Is there any way to modify it? Probably, if you take a look at this, you can understand the problem that am mentioning.

Related

Print values associated with checkboxes in HTML on button click event of JavaScript

Planning to get the specific ID values from the selection on the HTML page (selection here means checked boxes). Here is my code for a button click event(button will fetch the row numbers or ids):
$("a", button).click(function () {
$('#groups').find('tr').each(function () {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked')) {
console.log($(this));
}
});
});
This returns addtional information on rows + tr tag, however, I just want the ID part of it. Here is sample output I am getting out of above code:
[tr#row-12150.row.oddSelected, context: tr#row-12150.row.oddSelected]
[tr#row-12151.row.evenSelected, context: tr#row-12151.row.evenSelected]
This means I have selected 12150 and 12151 out of the #groups table. How do I just pull the row numbers 12150 and 12151 and not the entire detailed output and I want this to store in an array/(JS array) for multiple row numbers.
You have the row as per the .find('tr'), your should just be able to go:
console.log($(this).attr('id')); //this should show the id in your console.
so your code becomes:
$("a", button).click(function () {
$('#groups').find('tr').each(function () {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked')) {
console.log($(this).attr('id'));
}
});
});
Then to just get the number you can use:
var number = $(this).attr(id).split('-')[1] //assuming it's always row-<<some number>>
putting it all together:
$("a", button).click(function () {
$('#groups').find('tr').each(function () {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked')) {
var number = $(this).attr('id').split('-')[1] //assuming it's always row-<<some number>>;
console.log(number);
}
});
});
To store it in an array:
$("a", button).click(function () {
var checkedRows = []; //define empty array.
var count = 0; //keep a counter to use for the array.
$('#groups').find('tr').each(function () {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked')) {
var number = $(this).attr('id').split('-')[1];
checkedRows[count] = number; //add the number to our array.
count++; //increase the count
}
});
});
Make sure your form and your button have id's first then try this instead:
$('#buttonId').click(function(){
$('#formId input:checked').each(i, e){
console.log($(e).attr('id'));
}
});

Selectbox on change to effect within the same table row

I have 2 select boxes with class starttime and endtime and if startime is chosen then values in end time will be disabled which are prior to the starttime. At the moment as all classnames are same if I change one starttime its effecting all end times, is there anyway I can prevent changing the end time of other tables row?
JavaScript
$("select[class='starttime']").on("change", function(){
$("select[class='endtime']").empty();
var startix = $("select[class='starttime'] option:selected").index();
$("select[class='starttime'] option").each(function(ix, el){
if (ix >= startix) {
$(this).clone().appendTo("select[class='endtime']");
}
});
});
JSFiddle: http://jsfiddle.net/rt194bxd/
UPDATE 1
If that's not possible because of no proper identifier then will setting up id to TR (table row) does help in anyway?
I did setup id for each TR in this JSFiddle http://jsfiddle.net/rt194bxd/1/
Rather than doing .appendTo("select[class='endtime']");, appendTo the specific select element; i.e. the select element coming after the one that's clicked.
We have to traverse the DOM and find it.
$("select[class='starttime']").on("change", function () {
var $this = $(this);
var nextSelect = $this.parent().next().children().first();
nextSelect.empty();
var startix = $("select[class='starttime'] option:selected").index();
$("select[class='starttime'] option").each(function (ix, el) {
if (ix >= startix) {
$(this).clone().appendTo(nextSelect);
}
});
});
Update:
Above code is a bit buggy. The correct way is shown below:
$("select[class='starttime']").on("change", function () {
var $this = $(this);
var nextSelect = $this.parent().next().children().first();
console.log(nextSelect[0].tagName);
//$("select[class='endtime']").empty();
nextSelect.empty();
var startix = $("option:selected", $this).index();
$("option", $this).each(function (ix, el) {
if (ix >= startix) {
$(this).clone().appendTo(nextSelect);
}
});
});
Fiddle: http://jsfiddle.net/rt194bxd/4/
$("select.starttime").on("change", function(){
// Access "<tr />" elem.
// This can be resolved better (this assumes there will be exactly
// one select.starttime per row. I'd recommend giving [unique] ID to
// each row (or select.endtime) and passing it to select.starttime
// (in extra attribute perhaps).
var parent = $('tr')[$("select.starttime").index(this)];
var $this = $(this);
// Clear select.endtime of same table row
$("select.endtime", parent).empty();
// Get selected option index of this <select />
var startix = $("option:selected", $this).index();
// Run through this <select /> options
$("option", $this).each(function(ix, el){
if (ix >= startix) {
$("select.endtime", parent).append($(this).clone());
}
});
});

Click event object tracking woes

So I am working on this but of jQuery that gets the element id through a click event. This then triggers a function that acts like the deprecated .toggle()- it slides an element down on the fist click and slides that element up on the second click. However, there is a bug that causes the element to slide up and down the amount of times that it has been clicked on. For instance, if this is the second time I use the .clickToggle function, the element (table) slides up and down twice before settling, and so on. I suspect it has something to do with the event object, e, tracking the number of clicks-- i.e. I probably shouldn't set id = e.target.id-- but I'm not sure how to fix while still getting the relevant element id that I need.
Here is the relevant clickToggle plug in (courtesy of an answer here on stackoverflow).
(function($) {
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(funcs[tc], this)();
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
}(jQuery));
Here is the buggy code that fits the above description.
$(document).click(function(e) {
//get the mouse info, and parse out the relevant generated div num
var id = e.target.id;
var strId = id.match(/\d$/);
//clickToggle the individual table
$('#showTable' + strId).clickToggle(function () {
$('#table' + strId).slideDown();
$('#table' + strId).load('files.php');
},
function () {
$('#table' + strId).slideUp();
});
});//close mousemove function
Any help would be much appreciated. Thanks.
The problem is that you're registering a new click handler for the element each time you invoke clickToggle:
this.click(function() {...
On each subsequent click, you add another handler, as well as invoking all previous handlers. Bleagh.
Better to be straightforward: (DEMO)
var showTable = function($table) {
$table.slideDown();
$table.load('files.php');
$table.removeClass('hidden');
};
var hideTable = function($table) {
$table.slideUp();
$table.addClass('hidden');
};
$(document).click(function (e) {
//get the mouse info, and parse out the relevant generated div num
var id = e.target.id;
var strId = id.match(/\d$/)[0];
var $table = $('#table' + strId);
if ($table.hasClass('hidden')) {
showTable($table);
} else {
hideTable($table);
}
});

jQuery Tree issue - add first child li

I have 2 columns, on the left side a team with users, on the right column, will be displayed the users i have selected. so everything its working but i'm trying to implement a new feature as follow:
I have 2 list level like a tree (only 2 levels). When i click on a user, i'm able to select it sending to the right column. Also, when i click (single click) on the first level (team name), the second level (users) appear as toggle jquery function. i need so, when i double click on a team (level 1) all users on that tree turns selected and go to column on the right side.
Also, when i click on the team (first level) on the right side, all the users get removed back.
My code to add the users jquery current is:
$(document).ready(function () {
var maxAllowed = 10000;
var $selectTable = $("#mytable");
var $selectList = $("#selected_users ul")
$("#max-count").html(maxAllowed);
var getActivated = function () {
var activated = new Array();
$selectTable.find('input[type="checkbox"]:checked').closest("li").each(function () {
var $obj = new Object;
var currentBox = $(this).find('input[type="checkbox"]');
$obj.id = currentBox.val();
$obj.boxid = currentBox.attr("id");
$obj.name = $(this).find("label").text();
activated.push($obj);
});
return activated;
}
var updateActiveList = function () {
// Truncate list
$selectList.html("");
$(getActivated()).each(function () {
$selectList.append("<li><a href='#' class='remove' data-id='" + this.id + "' data-box-id='" + this.boxid + "'>" + this.name + "</li></a>");
});
}
var countActivated = function () {
return getActivated().length;
}
$('#view').click(function () {
allIds = new Array();
getActivated().each(function () {
allIds.push($(this).attr("id"));
});
alert(allIds);
});
$selectList.on("click", "a.remove", function () {
$('#' + $(this).data("box-id")).prop("checked", false);
updateActiveList();
});
$selectTable.on("change", 'input[type="checkbox"]', function (event) {
if ($(this).is(":checked") && countActivated() > maxAllowed) {
event.preventDefault();
console.log("max reached!");
$(this).prop("checked", false);
}
updateActiveList();
});
});
Here's a jsFiddle with working example:
http://jsfiddle.net/muzkle/LMbV3/7/
Thanks all!
EDIT
Hi, i just added a code to separate single click from double click. So when the user single click, will open the tree. now i need when the user double click on the first level, add both (first level and they're childrens to the right side.
Follow code for single and double clicks:
alreadyclicked=false;
$(document).ready(function () {
$('#mytable').on('click', '.toggle', function (ul) {
//Gets all <tr>'s of greater depth
//below element in the table
var findChildren = function (ul) {
var depth = ul.data('depth');
return ul.nextUntil($('ul').filter(function () {
return $(this).data('depth') <= depth;
}));
};
var el = $(this);
var ul = el.closest('ul'); //Get <tr> parent of toggle button
var children = findChildren(ul);
var el=$(this);
if (alreadyclicked){
alreadyclicked=false; // reset
clearTimeout(alreadyclickedTimeout); // prevent this from happening
}else{
alreadyclicked=true;
alreadyclickedTimeout=setTimeout(function(){
alreadyclicked=false; // reset when it happens
//Remove already collapsed nodes from children so that we don't
//make them visible.
//(Confused? Remove this code and close Item 2, close Item 1
//then open Item 1 again, then you will understand)
var subnodes = children.filter('.expand');
subnodes.each(function () {
var subnode = $(this);
var subnodeChildren = findChildren(subnode);
children = children.not(subnodeChildren);
});
//Change icon and hide/show children
if (ul.hasClass('collapse')) {
ul.removeClass('collapse').addClass('expand');
children.hide();
} else {
ul.removeClass('expand').addClass('collapse');
children.show();
}
return children;
// do what needs to happen on single click.
// use el instead of $(this) because $(this) is
// no longer the element
},300); // <-- dblclick tolerance here
}
return false;
});
});
And new jsFiddle is: http://jsfiddle.net/muzkle/LMbV3/8/
To distinguish different groups I am wrapping each group/section in a wrapper div with class .wrapper
<div class="wrapper">
.
.
</div>
Also I attached a double click event to .wrapper and currently I have made it to alert its inner labels.Just write some additional code to add these labels to the right side like you are currently adding one element on click.Below is the code with jQuery .dblclick() function which attaches a double-click event to .wrapper.
$('.wrapper').dblclick(function(){
$(this).find('label').each(function(){
alert($(this).text());
});
});
Check this fiddle

Dynamic Drop Down on iPhone

I'm trying to replicate the following Fiddle (http://jsfiddle.net/3UWk2/1/) on mobile (more specifically iPhone Safari) but it seems like it is not running the javascript correctly, any suggestions? Thanks!!
Here's the js:
<script>
$(document).ready(function() {
$('#00Ni0000007XPVF').bind('change', function() {
var elements = $('div.container_drop').children().hide(); // hide all the elements
var value = $(this).val();
if (value.length) { // if somethings' selected
elements.filter('.' + value).show(); // show the ones we want
}
}).trigger('change');
});
</script>
You seem to be using the cached value. hide does not return anything. So fails when you try to show them again.
var elements = $('div.container_drop').children().hide();
Supposed to be
var elements = $('div.container_drop').children();
elements.hide();
Code
$(document).ready(function() {
$('#00Ni0000007XPVF').bind('change', function() {
// cache the value
var elements = $('div.container_drop').children();
elements.hide(); // hide all the elements
var value = $(this).val();
if (value.length) { // if somethings' selected
elements.filter('.' + value).show(); // show the ones we want
}
}).trigger('change');
});

Categories

Resources