Target Array Value Directly After Selected One - javascript

I'm really sorry for I am aware similar questions have already been asked, but whenever I try to do it myself, none seem to apply or work. Basically when a user clicks on one of the elements, I am trying to get the following variables:
the id of the selected element
an array with all of the values prior to selected + selected one
an array with all of the values post-selected (selected not included)
the id of the element directly following the selected one
Thanks to your help in different posts, I have so far managed to complete the first two ones (in italic), but am unable to achieve the other two.
Would anyone know how to do so please? Thank you all in advance for your help!!
jQuery:
var days = ['#monday','#tuesday','#wednesday','#thursday','#friday','#saturday','#sunday'];
$('.days').on('click', function() {
var day = '#'+this.id;
var index = days.indexOf(day)+1;
var prev = days.slice(0, index);
var next = days.slice(index);
var above = days[index];
});

Should look more like this (though I really don't understand your code logic):
var dayIds = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday'];
$('.days').on('click', function() {
//get selected element id
var dayId = this.id;
//find selected position in array and delete all values after
var dayPos = dayIds.indexOf(dayId);
var daysBelow = dayIds.slice(0, dayPos + 1;
//find position of item directly after selected and get value
var dayAfterPos = dayIds.indexOf(dayId) + 1;
var dayAfter = dayIds[dayAfterPos]; //(not working)
//only keep values following selected one
...
console.log(floorsBelow, floorId);
});

This is how you need to slicing the array. I'm not sure all the requirements you have so I have just taken out a snippet to demonstrate how you can get your values.
var dayIds = new Array('#monday','#tuesday','#wednesday','#thursday','#friday','#saturday','#sunday');
const current = '#thursday';
const currentIndex = dayIds.indexOf(current)+1;
const prev = dayIds.slice(0, currentIndex);
const next = dayIds.slice(currentIndex);
console.log(current); //#thursday
console.log(prev); //[ '#monday', '#tuesday', '#wednesday', '#thursday' ]
console.log(next); // [ '#friday', '#saturday', '#sunday' ]
EDIT:
Added newVar to contain next value
var dayIds = new Array('#monday','#tuesday','#wednesday','#thursday','#friday','#saturday','#sunday');
const current = '#thursday';
const currentIndex = dayIds.indexOf(current)+1;
const prev = dayIds.slice(0, currentIndex);
const next = dayIds.slice(currentIndex);
const newVar = dayIds[currentIndex];
console.log(current); //#thursday
console.log(prev); //[ '#monday', '#tuesday', '#wednesday', '#thursday' ]
console.log(next); // [ '#friday', '#saturday', '#sunday' ]
console.log(newVar); // #friday

Related

getting the same random index for 2 arrays

I am building a flashcard web app and I am trying to make a random japanese character appear but at the same time also have a english value to the character.
So I have two arrays (one English and one Japanese) and I have, with the help of someone on here managed to get the random Japanese letter to be displayed.
my question is how do I get the same index value for the english array to check an answer against without breaking the rest of my code?
// kana indexes
var kanaArray = ["あ","い","う","え","お","か","き","く","け","こ","さ","し","す","せ","そ","た","ち","つ",
"て","と","な","に","ぬ","ね","の","は","ひ","ふ","へ","ほ","ま","み","む","め","も","や","ゆ","よ","ら","り","る",
"れ","ろ","わ","を","ん"]
var kanaEng = ["a","i","u","e","o","ka","ki","ku","ke","ko","sa","shi","su","se","so","ta","chi","tsu",
"te","to","na","ni","nu","ne","no","ha","hi","fu","he","ho","ma","mi","mu","me","mo","ya","yu","yo","ra","ri","ru",
"re","ro","wa","wo","n"]
let getRandomKana = () => kanaArray[Math.floor(Math.random()*kanaArray.length-1)];
let getAnswerVal = kanaEng[Math.floor(Math.random()*kanaEng.length-1)];
//logic
var started = false;
var level = 0;
let kanaPassed = [];
// start and switch buttons
$(document).ready(function(){
$(".startBtn").click(function(){
started = true
$('.startBtn').css("visibility", 'hidden');
$('.switchBtn').css("visibility", 'visible');
$('h3').text(getRandomKana());
$('h3').css("visibility",'visible');
console.log(started)
})
});
$('.switchBtn').click(function(){
$('h3').text(getRandomKana());
});
// check answer
$('.submit').click(function(){
console.log(getAnswerVal);
if($('#answerBox').val()===getAnswerVal){
$('card').css('background-color','red');
}
});
You can make sure to get the first array index and use the same index on the second array so that you can get the same translation. some what like this:
const kanaArray = ["あ","い","う","え","お","か","き","く","け","こ","さ","し","す","せ","そ","た","ち","つ","て","と","な","に","ぬ","ね","の","は","ひ","ふ","へ","ほ","ま","み","む","め","も","や","ゆ","よ","ら","り","る","れ","ろ","わ","を","ん"];
const kanaEng = ["a","i","u","e","o","ka","ki","ku","ke","ko","sa","shi","su","se","so","ta","chi","tsu","te","to","na","ni","nu","ne","no","ha","hi","fu","he","ho","ma","mi","mu","me","mo","ya","yu","yo","ra","ri","ru","re","ro","wa","wo","n"];
const randomIndex = Math.floor(Math.random()*kanaArray.length);
const randomKanaArray = kanaArray[randomIndex];
const randomKanaEng = kanaEng[randomIndex];
Also you can make it more easier if you store it with JSON obj:
const KANAS = [{jap: "あ", eng: "a"},...];
const RANDOM_KANAS= KANAS[Math.floor(Math.random()*KANAS.length)];
console.log(RANDOM_KANAS.jap, RANDOM_KANAS.eng);

Iterate through Id's, store values, put into an array

I want to be able to iterate through a number of ids called "#option1", "#option2" etc. The problem is its for an interactive form and I don't know how many options there will be. So I need a way to iterate through the amount in the DOM when the user clicks ("#dothis").
Then I need to get the values of the those options, put into an array called arraylist.
$("#doThis").on("click", function() {
var optionone = $("#option1").val();
var optiontwo = $("#option2").val();
var optionthree = $("#option3").val();
var optionfour = $("#option4").val();
var optionfive = $("#option5").val();
var arrayList = [optionone, optiontwo, optionthree,
optionfour, optionfive];
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
}); // end of dothis click event
As Andy said, give every option the same class. In my example it's "option-item".
$("#doThis").on("click", function() {
var arrayList = [];
$('.option-item').each(function(i) {
arrayList[i] = $(this).val();
});
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
});
Every value is now stored in the array.
see fiddle.
greetings timmi
With your code as is, you can use a selector that selects everything with an ID that starts with 'option', like so [id^="option"], here's how to use it:
$("#doThis").on("click", function () {
var arrayList = [];
$('[id^="option"]').each(function (index, element) {
arrayList.push($(element).val() );
});
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
}); // end of dothis click event

jQuery: How do I target the first duplicate list item?

I have a listing of events. I'd like to remove any events that have duplicate names and dates, but they can have different locations. I can successfully drop duplicates using a variation of code from this thread - JQuery: Remove duplicate elements? However I'd like to hide the location info for the first duplicate item and I can't seem to target that. Here is my code so far...
$('li').each(function() {
var name = $(this).find('.name').text();
var dates = $(this).find('.dates').text();
var nameAndDates = name + dates;
if (seen[nameAndDates]) {
$(this).remove();
}
else {
seen[nameAndDates] = true;
}
});
Somewhere in there I need to target the first duplicate item and add something along the lines of...
$(this).find('.location').hide();
Any ideas?
count them and remove only if first duplicate
var seen = {};
$('li').each(function() {
var name = $(this).find('.name').text();
var dates = $(this).find('.dates').text();
var nameAndDates = name + dates;
if (nameAndDates in seen && seen[nameAndDates] === 1) {
$(this).find('.location').hide();
}
seen[nameAndDates] = nameAndDates in seen ? seen[nameAndDates] + 1 : 1;
});

Find Index of Column(s) after it has been Moved

We are using DHTMLX Grid. Need some help, please.
I have a table and each columns (has filter/dropdown) are allocated an id eg. fac, date, sel, loc, tag ... etc
We have hard coded the index of columns to set and get the cookie elsewhere.
function doInitGrid(){
mygrid.setColumnIds("fac,date,sel,loc,tag"); //set ids
mygrid.attachEvent("onFilterStart",function(ind,data)
{
setCookie("Tray_fac_filter",mygrid.getFilterElement(0).value,365); //column index 0
setCookie("Tray_loc_filter",mygrid.getFilterElement(3).value,365);//column index 3
setCookie("Tray_tag_filter",mygrid.getFilterElement(4).value,365); //column index 4
mygrid.getFilterElement(0).value = getCookie("Tray_fac_filter")
mygrid.getFilterElement(3).value = getCookie("Tray_dep_filter")
mygrid.getFilterElement(4).value = getCookie("Tray_prg_filter")
});
}
But when the columns are moved, the problem arises as the index of the column changes yet it is set in setCookie /getCoookie
DHTMLX allows to get the index of the id using --
var colInd = grid.getColIndexById(id);
eg: var colInd = grid.getColIndexById(date); // outputs 1.
After moving the date column to the end -- fac, sel, loc, tag, date // it will output 4.
However, we have about 14 columns that can be moved/rearranged and I could use the
var colInd = grid.getColIndexById(id); 15 times
var facInd = grid.getColIndexById("fac");
var dateInd = grid.getColIndexById("date");
var selInd = grid.getColIndexById("sel");
var locInd = grid.getColIndexById("loc";
var tagInd = grid.getColIndexById("tag");
and put those variables in the set/get cookie. I was thinking if there was a better way.
To understand the code better, I have put the minimised version of the code in fiddle.
http://jsfiddle.net/19eggs/s5myW/2/
You've got the best answer I think. Do it in a loop and it's easier:
var cookie_prefix = "Fray_filter_";
var cookie_dur = 365;
var num_cols = dhx_grid.getColumnCount();
// filter vals to cookies
for (var col_idx=0; col_idx<num_cols; col_idx++) {
var filter = mygrid.getFilterElement(col_idx)
if (filter) { // not all columns may have a filter
var col_id = dhx_grid.getColumnId(col_idx);
var cookie_name = cookie_prefix+col_id;
setCookie(cookie_name, filter.value, cookie_dur);
}
}
// cookies to filter vals
for (var col_idx=0; col_idx<num_cols; col_idx++) {
var col_id = dhx_grid.getColumnId(col_idx);
var filter_val = getCookie(cookie_prefix+col_id);
var filter = mygrid.getFilterElement(col_idx)
filter.value = filter_val;
}
You can use dhtmlxgrid native event to assign the correct id everytime a column is moved.
The event is called onAfterCMove, you can check the documentation here. onAfterCMove Event
You would do something like:
mygrid.attachEvent('onAfterCMove',function(cInd,posInd){
//Your processing here to change the cookies; where cInd is the index of the column moved
//and posInd, is the position where it Was moved
}):

jquery get the unreapeatable values

i have a array with numbers. i need that array value to be generated once i click on the button, while i click on the button i need to get the value random wise from the array, but the value should not be repeated.
ex, if i get a 2 from out of 5, then i should not get the 2 again. for this i wrote this function, but the values are repeating... any idea?
var ar = [0,1,2,3,4,5];
var ran = Math.floor(Math.random()*ar.length);
ar.splice(ran,1);
alert(ar.splice);
the array values should not be removed. because if i click the button again, i need to get the values like before.
i did my work like this : but the rand values are repeating, any one can correct this to get unrepeatable values to get?
$(document).ready(function(){
var myArray = [1,2,3,4,5];
var mySize = 5;
x = 0;
while(mySize>=1){
var rand = Math.floor(Math.random()*mySize);
mySize--;
alert(rand);
}
})
You need your array to be in an outer scope for this like:
(function(){
var ar = [0,1,2,3,4,5];
document.getElementById('thebutton').onclick = function(){
alert(ar.splice(Math.floor(Math.random()*ar.length), 1));
};
})();
JSFiddle Example
If you create your array inside the onclick function then you are just recreating the entire array every time the button is clicked.
Take a look at this demo. In this it randomizes the array values and will repeat only after all the values are utilized.
Demo
Based on the update in your question here it is take a look.
http://jsfiddle.net/MbkwK/2/
var ar = [0, 1, 2, 3, 4, 5];
document.getElementById('thebutton').onclick = function() {
var shuffle = [];
var copyarr = ar.slice(0);
var arlength = copyarr.length;
for (i = 0; i < arlength; i++) {
shuffle.push(copyarr.splice(Math.floor(Math.random() * copyarr.length), 1));
}
alert(shuffle.join(","));
};
Working demo - http://jsfiddle.net/ipr101/qLSud/1/

Categories

Resources