I am trying to update a text on a click event, but somehow the index of the foreach always give me the first iteration 0, what am I missing:
var sliderTitles = document.getElementsByClassName('avia-caption-title');
var nextSlideBtns = document.getElementsByClassName('next-slide');
var prevSlideBtns = document.getElementsByClassName('prev-slide');
for (var i=0; i < nextSlideBtns.length; i++) {
nextSlideBtns.item(i).onclick = setBtnNames();
}
setBtnNames();
function setBtnNames() {
console.log("clickedd");
Array.from(nextSlideBtns).forEach(
function(element, index, array) {
console.log(index); // always returns 0
if(index == 5) {
element.innerHTML = sliderTitles[0].innerHTML;
} else {
element.innerHTML = sliderTitles[index+1].innerHTML;
}
}
);
}
Related
I am trying to use $.when apply in my code. However, it seems that the format return is different for single and multiple request. How can i cater for it?? I am trying not to have another if else outside of it.
$.when.apply(null, apiRequestList).then(function () {
for (var i = 0; i < arguments.length; i++) {
var value = arguments[0];
}
});
This is what i do not want to do.
if (apiRequestList.length === 1) {
$.ajax({
});
} else {
$.when.apply(null, apiRequestList).then(function () {
for (var i = 0; i < arguments.length; i++) {
var value = arguments[0];
}
});
}
You can simply convert arguments into an array, when the length of apiRequestList is 1:
$.when.apply(null, apiRequestList).then(function() {
var _arguments = Array.prototype.slice.call(arguments);
if (Array.isArray(apiRequestList) && apiRequestList.length === 1)
_arguments = [arguments];
for (var i = 0; i < _arguments.length; i++) {
var value = _arguments[i][0];
console.log(value);
}
});
Live Example on jsFiddle (since we can't do ajax on Stack Snippets):
function x(a) {
return $.post("/echo/html/", {
html: "a = " + a,
delay: Math.random()
});
}
function doIt(apiRequestList) {
$.when.apply(null, apiRequestList).then(function() {
var _arguments = arguments;
if (Array.isArray(apiRequestList) && apiRequestList.length === 1)
_arguments = [arguments];
for (var i = 0; i < _arguments.length; i++) {
var value = _arguments[i][0];
console.log(value);
}
console.log("----");
});
}
doIt([x(1), x(2), x(3)]);
doIt([x(4)]);
Example output (it'll vary because of the Math.random()):
a = 4
----
a = 1
a = 2
a = 3
----
I have a question. When querying my Json object, although i have my Field as same name and all Json rows available give me an error that is undefined.
//e.g: row.DepParentId
Bellow is my code. Am I missing some tag?
function convert(rows) {
debugger;
function exists(rows, parent) {
for (var i = 0; i < rows.length; i++) {
if (rows[i].DepId === parent) return true;
}
return false;
}
var nodes = [];
// get the top level nodes
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (!exists(rows, row.DepParentId)) {
nodes.push({
id: row.DepId,
name: row.Title
});
}
}
var toDo = [];
for (var i = 0; i < nodes.length; i++) {
toDo.push(nodes[i]);
}
while (toDo.length) {
var node = toDo.shift();
// the parent node
// get the children nodes
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (row.DepParentId == node.Id) {
var child = {
Id: row.DepId,
Name: row.Title
};
if (node.options) {
node.options.push(child);
} else {
node.options = [child];
}
toDo.push(child);
}
}
}
return nodes;
}
My Json example for one row picked from Firefox
"{"DepId":7,"DepParentId":3,"Title":"OTT"}"
Thanks for helping
Joao
thanks all for helping, it's working now, the problem was the JSON.stringify() was returning only an [Object] so when you use JSON.parse() generates a sintax error.
function onLoaded() {
var itemsCount = items.get_count();
for (var i = 0; i < itemsCount; i++) {
var item = items.itemAt(i);
var dep = JSON.stringify(item.get_fieldValues());
deps.push(dep);
}
So, i had to change the format to be valid to parse like this
var dt = "[" + deps + "]";
var ret = JSON.parse(dt);
Thanks
Joao
This code is designed to identify an array of anagrams for a string given an array of possible anagrams.
var anagram = function(input) {
return input.toLowerCase();
}
I'm adding the matcher function here to the String prototype.
String.prototype.matcher = function(remainingLetters) {
var clone = this.split("");
for (var i = 0; i < clone.length; i++) {
if (clone[i].indexOf(remainingLetters) > -1) {
remainingLetters.splice(clone[i].indexOf(remainingLetters, 1));
clone.splice(i, 1);
}
}
if (remainingLetters.length == 0 && clone.length == 0) {
return true;
}
else {
return false;
}
}
a
String.prototype.matches = function(matchWordArray) {
var result = [];
for (var i = 0; matchWordArray.length; i++) {
var remainingLetters = this.split("");
if (matchWordArray[i].matcher(remainingLetters)) {
result.push(arrayToMatch[i]);
}
}
return result;
}
var a = anagram("test");
a.matches(["stet", "blah", "1"]);
module.exports = anagram;
Should probably be:
for (var i = 0; i < matchWordArray.length; i++) {
The original statement:
for (var i = 0; matchWordArray.length; i++) {
...would result in an infinite loop because matchWordArray.length is always truthy (3) in your test.
I am creating array object like follows:
var numberOfSameDeficiency = [];
for (var i = 0; i < result.length; i++) {
var deficiencyId = result[i].Deficiency_Id;
var deficiencyName = result[i].DeficiencyName;
//check to see if this deficiency is already in the list of available selections
if ($("#drpDeficiency option[value='" + deficiencyId + "']").length == 0) {
var option = $('<option>');
option.attr('value', deficiencyId);
option.text(deficiencyName);
$select.append(option);
}
else {
Tests = {};
Tests.TestId = testId;
Tests.DeficiencyId = deficiencyId;
numberOfSameDeficiency.push(Tests);
}
}
And I want to remove object on different function like this:
for (var i = 0; i < result.length; i++) {
console.log(numberOfSameDeficiency);
var isFound = false;
var deficiencyId = result[i].Deficiency_Id;
if (numberOfSameDeficiency) {
numberOfSameDeficiency.forEach(function (entry) {
if (entry.DeficiencyId != deficiencyId) {
isFound = true;
**numberOfSameDeficiency.splice(entry, 1); // Generating Error (Remove all items from array object)**
return;
}
});
// console.log("end if");
}
if (!isFound) {
$("#drpDeficiency option[value='" + deficiencyId + "']").remove();
}
}
So what line code should be there to remove particular object from array object.
Try this
for( i=myArray.length-1; i>=0; i--) {
if( myArray[i].field == "money") myArray.splice(i,1);
}
This also works
myArray = [{name:"Alpesh", lines:"2,5,10"},
{name:"Krunal", lines:"1,19,26,96"},
{name:"Deep",lines:"3,9,62,36" }]
johnRemovedArray = myArray
.filter(function (el) {
return el.name !== "Krunal";
});
Create this prototype function:
Array.prototype.removeElement = function (el) {
for(let i in this){
if(this.hasOwnProperty(i))
if(this[i] === el)
this.splice(i, 1);
}
}
Then call:
let myArray = ['a','b','c','d'];
myArray.removeElement("c");
It also works with objects:
let myObj1 = {name: "Mike"},
myObj2 = {name: "Jenny"},
myArray = [myObj1, myObj2];
myArray.removeElement(myObj2);
Im not sure why this isnt working and would love some help with it! And yes i have looked at this
Im trying to set multiple options in a select element as selected using an array holding the values i want selected and interating through both the array and the options in the select element. Please find code below:
// value is the array.
for (var j = 0; j < value.length; j++) {
for (var i = 0; i < el.length; i++) {
if (el[i].text == value[j]) {
el[i].selected = true;
alert("option should be selected");
}
}
}
After completing these loops nothing is selected, even though the alert() fires.
Any ideas are welcome!
Thanks
CM
PS (not sure whats happened to the code formatting).
EDIT: Full function
if (CheckVariableIsArray(value) == true) {
if (value.length > 1) { // Multiple selections are made, not just a sinle one.
var checkBoxEl = document.getElementById(cbxElement);
checkBoxEl.checked = "checked";
checkBoxEl.onchange(); // Call function to change element to a multi select
document.getElementById(element).onchange(); // Repopulates elements with a new option list.
for (var j = 0; j < value.length; j++) {
for (var i = 0; i < el.length; i++) {
if (el[i].text === value[j]) {
el[i].selected = true;
i = el.length + 1;
}
}
}
//document.getElementById(element).onchange();
}
}
else {
for (var i = 0; i < el.length; i++) {
if (el[i].innerHTML == value) {
el.selectedIndex = i;
document.getElementById(element).onchange();
}
}
}
Works for me. Are you setting el and value correctly? And are you sure you want to look at each option's innerHTML instead of it's value attribute?
See the jsFiddle.
HTML:
<select id="pick_me" multiple="multiple">
<option>Hello</option>
<option>Hello</option>
<option>Foo</option>
<option>Bar</option>
</select>
JS:
var value = ['Foo', 'Bar'],
el = document.getElementById("pick_me");
// value is the array.
for (var j = 0; j < value.length; j++) {
for (var i = 0; i < el.length; i++) {
if (el[i].innerHTML == value[j]) {
el[i].selected = true;
//alert("option should be selected");
}
}
}
Well, first of all, you must set the html select control multiple property, something like this "<select multiple="multiple">...</select>", and then you can use the javascript function SetMultiSelect (defined as below) to set the select html control:
function SetMultiSelect(multiSltCtrl, values)
{
//here, the 1th param multiSltCtrl is a html select control or its jquery object, and the 2th param values is an array
var $sltObj = $(multiSltCtrl) || multiSltCtrl;
var opts = $sltObj[0].options; //
for (var i = 0; i < opts.length; i++)
{
opts[i].selected = false;//don't miss this sentence
for (var j = 0; j < values.length; j++)
{
if (opts[i].value == values[j])
{
opts[i].selected = true;
break;
}
}
}
$sltObj.multiselect("refresh");//don't forget to refresh!
}
$(document).ready(function(){
SetMultiSelect($sltCourse,[0,1,2,3]);
});
Ran into this question and wasn't satisfied with the answers.
Here's a generic, non-jQuery version. It utilises Array.indexOf where possible, but falls back to a foreach loop if it isn't available.
Pass a node into the function, alongside an array of values. Will throw an exception if an invalid element is passed into it. This uses === to check against the value. For the most part, make sure you're comparing the option's value to an array of strings.
E.g. selectValues( document.getElementById( 'my_select_field' ), [ '1', '2', '3'] );
var selectValues = (function() {
var inArray = ( function() {
var returnFn;
if( typeof Array.prototype.indexOf === "function" ) {
returnFn = function(option, values) {
return values.indexOf( option.value ) !== -1;
};
} else {
returnFn = function(option, values) {
var i;
for( i = 0; i < values.length; i += 1 ) {
if( values[ i ] === option.value ) {
return true;
}
}
return false;
}
}
return returnFn;
}() );
return function selectValues(elem, values) {
var
i,
option;
if( typeof elem !== "object" || typeof elem.nodeType === "undefined" )
throw 'selectValues() expects a DOM Node as it\'s first parameter, ' + ( typeof elem ) + ' given.';
if( typeof elem.options === "undefined" )
throw 'selectValues() expects a <select> node with options as it\'s first parameter.';
for( i = 0; i < elem.options.length; i += 1 ) {
option = elem.options[ i ];
option.selected = inArray( option, values );
}
}
}());