I have a function that swaps the selected item in a select box (listbox) with the item above it which works ok but I want to make it so that the item is still selected afterwords. So if the user wanted to keep moving the item upwards in the box he could keep pressing the Move Up button.
function moveUp() {
var list = document.getElementById('listbox');
var numSelected = list.selectedIndex;
var itemSelected = list.options;
if (itemSelected[numSelected].id == 0) {
alert("Can't move this up the list!");
} else {
if (poiArrayList[numSelected - 1] != null) {
var tempPOI = poiArrayList[numSelected];
poiArrayList[numSelected] = poiArrayList[numSelected - 1];
poiArrayList[numSelected - 1] = tempPOI;
//The line below is what I have but that doesn't seem to work.
list.selectedIndex = numSelected;
} else {
alert("The listbox is empty!");
}
}
}
Full code
Have a look here: http://jsfiddle.net/2ae9B/1/
I've added an optional parameter to generateListBox(), where you can set the index to be highlighted once the list is generated. For example:
function moveUp() {
var list = document.getElementById('listbox');
var numSelected = list.selectedIndex;
...
...
// regenerate the list passing the item to select
generateListBox(numSelected - 1);
}
and
function generateListBox(selectedIndex) {
var selectBox = document.getElementById("listbox");
selectBox.innerHTML = "";
for (var i = 0; i < poiArrayList.length; i++) {
lbAddItem(poiArrayList[i].name, i);
}
// you should also check that is a valid integer here
if(selectedIndex)
selectBox.selectedIndex = selectedIndex;
}
Hope it helps
Related
My jQuery checkbox filter works normally:
http://jsfiddle.net/EducateYourself/Lmehmj26/3/
Under checkbox form I want to show the number of results. It is 7 by default.
When I filter the results, it does not show the correct number of displayed results.
Could you please help me to find my mistake?
I commented the lines in my jsfiddle code where I added variable n to achieve the result I want.
$('.category').on('change', function () {
var n; //declare variable n
var category_list = [];
$('#filters :input:checked').each(function () {
var category = $(this).val();
category_list.push(category);
});
if (category_list.length == 0) {
$('.resultblock').show();
} else {
$('.resultblock').hide();
});
$('#count').text(n); // change the results qunatity
}
});
The problem is that you are incrementing n multiple times for a single element if it contains multiple matching tags.
You should only increment n once, at most, for each element:
Updated Example
$('.resultblock').each(function() {
var item = $(this).data('tag'),
itemArray = item.split(' '),
hasTag = false;
for (var i = 0; i < category_list.length; ++i) {
if (itemArray.indexOf(category_list[i]) >= 0) {
hasTag = true;
}
}
if (hasTag) {
$(this).show();
n++; // Only increment n once, at most, for each element.
}
});
Here is a cleaner, simplified version of your code:
Updated Example
$('.category').on('change', function() {
var categoryList = $('#filters :input:checked').map(function() {
return this.value;
}).get();
var count = 0;
$('.resultblock').hide().each(function() {
var itemTagsArray = $(this).data('tag').split(' ');
var hasTag = false;
categoryList.forEach(function(tag) {
if (itemTagsArray.indexOf(tag) > -1) {
hasTag = true;
}
});
if (hasTag) {
$(this).show();
count++;
}
});
$('#count').text(count);
});
You're counting doubles, a very easy fix is to add a check for visibility in your for loop like so
for (i = 0; i < category_list.length; ++i) {
if (itemArray.indexOf(category_list[i]) >= 0 && !$(self).is(":visible")) {
$(self).show();
n=n+1; //increase the value of n if found a result
}
}
As shown in this fiddle, that works
As a sidenote, your numbering breaks when you've selected one or more checkboxes and then deselect all. To prevent this you should change your check if there's been any checkboxes checked to
if (category_list.length == 0) {
$('.resultblock').show();
$('#count').text($('.resultblock').length);
}
i have a div with multiple images inside and i need to click on a random image then again click on a random picture and when i clicked the second image to change images with each other. All images are interchangeable.Heres what i've done so far:
EDIT FIDDLE: http://jsfiddle.net/w53Ls/5/
$("#image1").click(function(){
imagePath = $("#image2").attr("src");
if(imagePath == "http://s15.postimg.org/oznwrj0az/image.jpg"){
$("#image3").attr("src", "http://s21.postimg.org/ojn1m2eev/image.jpg");
}else{
$("#image4").attr("src", "http://s23.postimg.org/epckxn8uz/image.jpg");
}
});
EDIT: The code i have tryed for check function is in EDIT FIDDLE and with the alert i check src of pictures.Now i simply need to make a condition to alert something after i change all the pieces in order and found the whole picture.Any hint?
DEMO
var clickCount = 0;
var imgSrc;
var lastImgId;
$("img.element").click(function(){
if (clickCount == 0)
{
imgSrc = $(this).attr("src");
lastImgId = $(this).attr("id");
clickCount++;
}
else {
$("#"+lastImgId).attr("src",$(this).attr("src"));
$(this).attr("src",imgSrc)
clickCount = 0;
}
});
Updated
This let's you know when you're done with the puzzle
DEMO
var clickCount = 0;
var imgSrc;
var lastImgId;
// Function for Comparing Arrays
// source: http://stackoverflow.com/questions/7837456/
Array.prototype.compare = function (array) {
if (!array) return false;
if (this.length != array.length) return false;
for (var i = 0, l = this.length; i < l; i++) {
if (this[i] instanceof Array && array[i] instanceof Array) {
if (!this[i].compare(array[i])) return false;
} else if (this[i] != array[i]) {
return false;
}
}
return true;
}
$(document).ready(function () {
// Store the correct order first in an array.
var correctOrder = $("#puzzle > img").map(function () {
return $(this).attr("src");
}).get();
// Randomize your images
var a = $("#puzzle > img").remove().toArray();
for (var i = a.length - 1; i >= 1; i--) {
var j = Math.floor(Math.random() * (i + 1));
var bi = a[i];
var bj = a[j];
a[i] = bj;
a[j] = bi;
}
$("#puzzle").append(a);
$("img.element").click(function () {
if (clickCount == 0) {
imgSrc = $(this).attr("src");
lastImgId = $(this).attr("id");
clickCount++;
} else {
$("#" + lastImgId).attr("src", $(this).attr("src"));
$(this).attr("src", imgSrc);
clickCount = 0;
// Get the current order of the images
var currentOrder = $("#puzzle > img").map(function () {
return $(this).attr("src");
}).get();
// Compare the current order with the correct order
if (currentOrder.compare(correctOrder)) alert("Puzzle completed");
}
});
});
http://jsfiddle.net/w53Ls/2/
var counter = 0;
The code was improvised but works XD
you try improve it
Here is a new version of your jsfiddle that I think will do what you want.
It applies the same click handler to every object with the class swapable. Each time a swapable element is clicked, the handler checks whether another element was previously clicked first. If so, it swaps them. If not, it just remembers that this element is the first one.
var firstId = ''; // Initially, no element has been clicked first
var firstSrc = '';
// Apply the following function to every element with 'class="swapable"
$('.swapable').click(function(){
if (firstId !== '') { // There is already a first element clicked
// Remember the information of the currently clicked element
var secondId = $(this).attr('id');
var secondSrc = $(this).attr('src');
// Replace the currently clicked element with the first one
$('#' + secondId).attr('src', firstSrc);
// Replace the first one with the current one
$('#' + firstId).attr('src', secondSrc);
// Forget the first one, so that the next click will produce a new first
firstId = '';
firstSrc = '';
}
else // This is the first element clicked (this sequence)
{
// Remember this information for when a second is clicked
firstId = $(this).attr('id');
firstSrc = $(this).attr('src');
}
});
How to delete two rows at a time using JavaScript even though only for first row radio button exist?
Something like this:
1st row: (radiobutton) some textfield
2nd row: text field
On click of delete button, both the row should get deleted but the code which I have written is deleting only 1st row not 2nd one.
JavaScript code looks something like this:
function deleteReserveDetails() {
if (!document.forms[0].reserveRadiobutton) {
return;
} else {
var hidValue = parseInt(document.forms[0].Hd1Value.value);
var reserveRows = document.getElementById('reserveTable').getElementsByTagName('tr');
var headerNo = 1;
var radio = eval("document.forms[0].reserveRadiobutton");
if (radio.length == undefined) {
if (radio.checked) {
var hidValue1 = parseInt(document.forms[0].Hd1Value.value) - 1;
document.forms[0].Hd1Value.value = hidValue1;
document.getElementById('reserveTable').deleteRow(headerNo);
}
return;
}
var k = 0;
for (var j = 0; j < radio.length; j++) {
if (radio[j].checked) {
if (j == hidValue - 1) {
var hidValue2 = parseInt(document.forms[0].Hd1Value.value) - 1;
document.forms[0].Hd1Value.value = hidValue2;
}
document.getElementById('reserveTable').deleteRow(j + headerNo);
}
}
}
}
Could you please show me how to modify it to delete 2 rows at a time?
function listbox_moveacross(sourceID, destID) {
var src = document.getElementById(sourceID);
var dest = document.getElementById(destID);
var errCount = 0;
for (var count = 0; count < src.options.length; count++) {
if (src.options[count].selected == true) {
var option = src.options[count];
var newOption = document.createElement("option");
newOption.value = option.value;
newOption.text = option.text;
newOption.selected = true;
try {
dest.add(newOption, null); // Standard
src.remove(count, null);
} catch (error) {
dest.add(newOption); // IE only
src.remove(count);
}
count--;
errCount++;
}
}
if (errCount == 0) {
alert("No Element Selected or you have no element to move");
}
}
Hi Can any body help on JavaScript Given code will be for moving list of values from Right to Left and Left to user can select the multiple values in given list but in my case i am unable to move list of values from Right to Left but it is working fine with Left to Right
try removing count--; from your code I have a feeling this is preventing the loop from moving onto the next iteration if it finds a selected item in the list.
seems to work fine to me:
http://jsfiddle.net/xBDKg/
I need guidance editing a file. I have posted the Javascript below. This is a link to my working example http://www.closetos.com/top-shelf-awards_copy_copy.
The problem occurred when I added an additional row to the table. Now, when you select the text link in a cell in the second row, it stays selected and active, when clicking on something in the top row.
function $(id)
{
return document.getElementById(id);
}
function Coalesce(Value, Default)
{
if(Value == null)
return Default;
return Value;
}
function Switcher(numberOfSections, sectionContainerID, activeClass, inactiveClass)
{
this.NumberOfSections = Coalesce(numberOfSections, 1) - 1;
this.SectionContainerID = Coalesce(sectionContainerID, "sectionContainer");
this.ActiveClass = Coalesce(activeClass, "active");
this.InactiveClass = Coalesce(inactiveClass, "");
}
Switcher.prototype.Switch = function(TheLink, SectionID)
{
// Make sure all sections are hidden
var SectionContainer = $(this.SectionContainerID);
for(var ct = 0; ct < SectionContainer.childNodes.length; ct++)
{
var node = SectionContainer.childNodes[ct];
if(node.nodeType != 1)
continue;
node.style.display = "none";
}
var First = true;
// Reset button styles
for(var ct = 0; ct < TheLink.parentNode.childNodes.length; ct++)
{
if(TheLink.parentNode.childNodes[ct].nodeType != 1)
continue;
else node = TheLink.parentNode.childNodes[ct];
node.className = this.InactiveClass;
if(First)
{
node.className += " firstCell";
First = false;
}
}
// Show the selected section
$(SectionID).style.display = "block";
TheLink.className = this.ActiveClass;
if(TheLink == node)
TheLink.className += " lastCell";
}
You problem is in this section of code. this looks only at the row that the clicked cell is in. TheLink.parentNode is a reference to the row that the cell is in.
for(var ct = 0; ct < TheLink.parentNode.childNodes.length; ct++) <--- parenNode == row
{
if(TheLink.parentNode.childNodes[ct].nodeType != 1)
{
continue;
}
else
{
node = TheLink.parentNode.childNodes[ct];
}
node.className = this.InactiveClass;
if(First)
{
node.className += " firstCell";
First = false;
}
}
In order to make this work with multiple rows you need to modify it to look at other rows in the table:
for(var ct = 0; ct < TheLink.parentNode.parentNode.childNodes.length; ct++)
{
for( innerL = 0; innerL < TheLink.parentNode.parentNode.childNodes[ct].childNodes.length; innerL++)
{
if(TheLink.parentNode.parentNode.childNodes[ct].childNodes[innerL].nodeType != 1)
{
continue;
}
else
{
node = TheLink.parentNode.parentNode.childNodes[ct].childNodes[innerL];
}
node.className = this.InactiveClass;
if(First)
{
node.className += " firstCell";
First = false;
}
}
}
in the block above you are looking at the parentNode's (the tr) parentNode (tbody) and then iterating through its grandchildren. This allows you to capture all the cells in the table, not just the row.
Here is an example of it working. When you follow the link you need to hit the green 'run' button on the bottom left of the page to get the script to load.