Check a value from Array in javascript? - javascript

I have a:
var pageURL = location.href; // stores the URL of the current page in the var pageURL
And I have :
var Page = Array ();
page [0] = "http://web1.com"
page [1] = "http://web2.com"
page [2] = "http://web3.com"
Now I want to make a function (called nextPage) to check which one of these pages in the array equals the PageURL. Also I need to have a button, so when I click it it will take me to the next page. What that mean I want to increment the page by 1.

You can use very simply
var current = page.indexOf(location.href);
Then to go to the next page
location.href = page[current + 1];

var form = document.createElement('form');
form.id = "nextForm";
document.body.appendChild(form);
var nextButton = document.createElement('input');
nextButton.type = 'button';
nextButton.id = 'nextButton';
nextButton.value = 'Next Button';
nextButton.onclick = nextPage;
form.appendChild(nextButton);
function nextPage() {
var page = Array ();
page[0] = "http://web1.com" // insert your urls here
page[1] = "http://web2.com"
page[2] = "http://web3.com"
var matchIndex = page.indexOf(location.href);
var nextIndex;
if (matchIndex !== -1 && page[matchIndex + 1]) {
nextIndex = matchIndex + 1;
} else {
alert("You're at the last page"); // next page in the array does not exist, you can handle the error however you want
return;
}
goToNextPage(page[nextIndex]);
}
function goToNextPage(url) {
document.location.href=url;
}

Based on Joseph's answer the full code would look something like this:
function goToNextPage() {
var currentPageUrl = location.href;
var pageUrls = [
"http://web1.com",
"http://web2.com",
"http://web3.com"
];
var currentIndex = pageUrls.indexOf(location.href);
var nextIndex = currentIndex + 1;
var nextPageUrl = pageUrls[nextIndex];
location.href = nextPageUrl;
}
Also if support for indexOf is an issue for you in IE check out the answer to that from another StackOverflow question: How to fix Array indexOf() in JavaScript for Internet Explorer browsers

Related

Looping error in Javascript with eventHandler

I have the following Javascript code within and HTML page. Its function is to display elements on the form based on the user pressing a + button and if the element is not needed then it removes it via the user pressing the - button. Currently its throwing an error "TypeError: docs[n]" is undefined after the following sequence of events:
Select button to add elements
Remove elements not needed
Add elements back (Error Thrown)
Any help would be most appreciated
`<script language="JavaScript">`
var idx = 0;
var d;
//Make getElementsByClassName work for all of IE revs
if (!document.getElementsByClassName) {
document.getElementsByClassName = function (cn) {
var rx = new RegExp("(?:^|\\s)" + cn+ "(?:$|\\s)");
var allT = document.getElementsByTagName("*"), allCN = [],ac="", i = 0, a;
while (a = allT[i=i+1]) {
ac=a.className;
if ( ac && ac.indexOf(cn) !==-1) {
if(ac===cn){ allCN[allCN.length] = a; continue; }
rx.test(ac) ? (allCN[allCN.length] = a) : 0;
}
}
return allCN;
}
}
function add_fields(e) {
// for some reason, adding the new fields wipes out existing values, so save and restore
var docs = document.getElementsByClassName("doc");
var revs = document.getElementsByClassName("rev");
++idx;
/* console.log("test " + idx); */
var saveDocs = new Array(idx);
var saveRevs = new Array(idx);
for (n=0; n < idx; n++) {
saveDocs[n] = docs[n].value; **//Error is thrown here**
saveRevs[n] = revs[n].value;
}
node = document.getElementById("content");
theNewRow = document.createElement("tr");
theNewCell = theNewRow.insertCell(0);
theNewCell.innerHTML = "Approver Name";
theNewCell.setAttribute("style","font-size: 12pt");
theNewCell1 = theNewRow.insertCell(1);
theNewCell1.innerHTML = "<input type='text' class='doc' style='width:180px;' id='docNum0'/>";
theNewCell1.setAttribute("style","padding-left: 10px");
theNewCell2 = theNewRow.insertCell(2);
theNewCell2.innerHTML = "Approver Email";
theNewCell2.setAttribute("style","font-size: 12pt");
theNewCell2.setAttribute("style","padding-left: 10px");
theNewCell3 = theNewRow.insertCell(3);
theNewCell3.innerHTML = "<input type='text' class='rev' style='width:180px;' id='rev0'/> <input class='minusThing' type='button' style='font-size:10px' value='- '/>";
theNewCell3.setAttribute("style","padding-left: 0px");
node.appendChild( theNewRow );
// restore old arrays and add the id tags to the fields just added
docs = document.getElementsByClassName("doc");
revs = document.getElementsByClassName("rev");
for (n=0; n < idx; n++) {
docs[n].value = saveDocs[n];
revs[n].value = saveRevs[n];
}
docs[idx].id = "docNum" + idx;
revs[idx].id = "rev" + idx;
}
//for Loop the entries
function myfunction() {
alert('Inside Function')
var values = "";
for (n=0; n <= idx; n++)
{
var doc = document.getElementById("docNum"+n).value;
var rev = document.getElementById("rev"+n).value;
//alert(doc+rev);
//Call VbScript Sub and pass value
PassValues(doc,rev);
```
If you've removed all the docs, document.getElementsByClassName("doc"); is going to return an empty array. If you're incrementing idx before your loop, the loop will execute once and try to access docs[0], which is undefined.

Updating value in for loop / Reseting a for loop?

I'm working on my first school project so I don't have much experience in doing such web applications, that's why I decided to ask here.
How can I update the value in the for loop syntax or reset it entirely, so it iterates again, like I just reloaded it? I have another function that I decided not to show, simply because it would be useless to. What it does in the end is increments the taskCount.length by one. This part technically works but problem is, the function I'm going to show you now, once iterated, will always keep the default taskCount.length value, once the page is loaded, it never changes there. Is there any way I can update it?
Here's an example: The function above makes taskCount.length = '5' but when the page started it was taskCount.length = 4, and when I do alert(taskCount.length) from the console, I get 5. But the for loop doesn't want to change.
for (var i = 0; i < taskCount.length; i++) {
document.getElementsByClassName('task')[i].addEventListener('click', ((j) => {
return function() {
var shadow = document.createElement('div');
// Styling
var changingWindow = document.createElement('div');
// Styling
var changingTitle = document.createElement('p');
// Styling
var changingText = document.createElement('p');
// Styling
var changingTitleNode = document.createTextNode('Промяна');
var changingTextNode = document.createTextNode('Моля, изберете действие.');
var deleteTask = document.createElement('button');
var goUp = document.createElement('button');
var goDown = document.createElement('button');
var unchange = document.createElement('button');
// Styling
var deleteElementNode = document.createTextNode('Премахни задачата');
var goUpNode = document.createTextNode('Премести нагоре');
var goDownNode = document.createTextNode('Премести надолу');
var unchangeNode = document.createTextNode('Отказ');
var justBreak = document.createElement('br');
var justBreakAgain = document.createElement('br');
var justBreakOneMoreTime = document.createElement('br');
body.appendChild(shadow);
shadow.appendChild(changingWindow);
changingWindow.appendChild(changingTitle);
changingTitle.appendChild(changingTitleNode);
changingWindow.appendChild(changingText);
changingText.appendChild(changingTextNode);
changingWindow.appendChild(deleteTask);
deleteTask.appendChild(deleteElementNode);
deleteTask.onclick = function() {
document.getElementsByClassName('task')[j].parentNode.removeChild(document.getElementsByClassName('task')[j]);
shadow.parentNode.removeChild(shadow);
localStorage.setItem("listContent", document.getElementById('list').innerHTML);
}
changingWindow.appendChild(justBreak);
changingWindow.appendChild(goUp);
goUp.appendChild(goUpNode);
goUp.onclick = function() {
if (j !== 0) {
var saveThisTaskValue = document.getElementsByClassName('task')[j].innerHTML;
var savePreviousTaskValue = document.getElementsByClassName('task')[j - 1].innerHTML;
document.getElementsByClassName('task')[j].innerHTML = savePreviousTaskValue;
document.getElementsByClassName('task')[j - 1].innerHTML = saveThisTaskValue;
}
shadow.parentNode.removeChild(shadow);
localStorage.setItem("listContent", document.getElementById('list').innerHTML);
}
changingWindow.appendChild(justBreakAgain);
changingWindow.appendChild(goDown);
goDown.appendChild(goDownNode);
goDown.onclick = function() {
if (j !== document.getElementsByClassName('task').length - 1) {
var saveThisTaskValue = document.getElementsByClassName('task')[j].innerHTML;
var saveNextTaskValue = document.getElementsByClassName('task')[j + 1].innerHTML;
document.getElementsByClassName('task')[j].innerHTML = saveNextTaskValue;
document.getElementsByClassName('task')[j + 1].innerHTML = saveThisTaskValue;
}
shadow.parentNode.removeChild(shadow);
localStorage.setItem("listContent", document.getElementById('list').innerHTML);
}
changingWindow.appendChild(justBreakOneMoreTime);
changingWindow.appendChild(unchange);
unchange.appendChild(unchangeNode);
unchange.onclick = function() {
shadow.parentNode.removeChild(shadow);
}
}
})(i))
}
As a matter of the page reloading, you can always save the value as a cookie and reuse it again and again. You can update it whenever you want.
I don't fully understand you question, but maybe some recursion is what you need. Something along the lines of:
loop(5);
function loop(xTimes) {
for (var i = 0; i < xTimes; i++) {
if (newXTimes !== xTimes) {
loop(newXtimes);
break;
}
}
}
Maybe set newxTimes as a global variable that can be accessed inside loop.
In case someone "from the future" reads this question and it doesn't have any answers, I came up with the solution to reload the page everytime you change the value. Still, I'd like to do it without reloading.

Accessing Stored Object

I have an object "Driver" defined at the beginning of my script as such:
function Driver(draw, name) {
this.draw = draw;
this.name = name;
}
I'm using this bit of JQuery to create new drivers:
var main = function () {
// add driver to table
$('#button').click(function ( ) {
var name = $('input[name=name]').val();
var draw = $('input[name=draw]').val();
var draw2 = "#"+draw;
var name2 = "driver"+draw
console.log(draw2);
console.log(name2);
if($(name2).text().length > 0){
alert("That number has already been selected");}
else{$(name2).text(name);
var name2 = new Driver(draw, name);}
});
That part is working great. However, when I try later on to access those drivers, the console returns that it is undefined:
$('.print').click(function ( ) {
for(var i=1; i<60; i++){
var driverList = "driver"+i;
if($(driverList.draw>0)){
console.log(driverList);
console.log(driverList.name);
}
If you're interested, I've uploaded the entire project I'm working on to this site:
http://precisioncomputerservices.com/slideways/index.html
Basically, the bottom bit of code is just to try to see if I'm accessing the drivers in the correct manner (which, I'm obviously not). Once I know how to access them, I'm going to save them to a file to be used on a different page.
Also a problem is the If Statement in the last bit of code. I'm trying to get it to print only drivers that have actually been inputed into the form. I have a space for 60 drivers, but not all of them will be used, and the ones that are used won't be consecutive.
Thanks for helping out the new guy.
You can't use a variable to refer to a variable as you have done.
In your case one option is to use an key/value based object like
var drivers = {};
var main = function () {
// add driver to table
$('#button').click(function () {
var name = $('input[name=name]').val();
var draw = $('input[name=draw]').val();
var draw2 = "#" + draw;
var name2 = "driver" + draw
console.log(draw2);
console.log(name2);
if ($(name2).text().length > 0) {
alert("That number has already been selected");
} else {
$(name2).text(name);
drivers[name2] = new Driver(draw, name);
}
});
$('.print').click(function () {
for (var i = 1; i < 60; i++) {
var name2 = "driver" + i;
var driver = drivers[name2];
if (driver.draw > 0) {
console.log(driver);
console.log(driver.name);
}

Javascript: Passing Value of Tag to a Variable

Hope you can help me find a solution to this issue. I have a page with a number of anchor tags that contain an ID with a unique element. Here's a sample of the links:
<a href="#" class="button" id="widget_1"
onclick="$(this).parent().submit(); return false;">Button</a>
<a href="#" class="button" id="widget_2"
onclick="$(this).parent().submit(); return false;">Button</a>
<a href="#" class="button" id="widget_3"
onclick="$(this).parent().submit(); return false;">Button</a>
Below is the code that I tried to create to do collect the values in "id":
var num = [];
for (var i = 0; i<11; i++) {
num[i] = document.getElementsByTagName("id")[i].textContent;
if (num[i] == "widget_1"){ var y = "39.00"; return y;}
else if (num[i] == "widget_2"){ var y = "59.00"; return y;}
else if (num[i] == "widget_3"){ var y = "85.00"; return y;}
else { var y = "0";}
return y; }
What I'm trying to do is capture what's on id and use it to pass it to the array and if the contents match, then return the value of "y". For example, if I click on the second link, then 59.00 is returned. Any help that can be provided will be greatly appreciated.
Thanks,
Ridder
Another Approach
This approach also allows you to remove the onclick events in markup and improve readability, separating behavior from structure. (aka Separation of Concerns)
// put your prices on an array;
var prices = [39.0, 59.0, 85.0];
// match all widget(s) (aka anchors), add click handler.
$("[id^=widget]").click(function(element) {
// calculate the index into prices array based on anchor id.
var index = parseInt(this.id.substring(7)) - 1;
// get the pirce
var price = prices[index];
alert("Price is: " + price);
// here you could call
// this.$parent.submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Button
Button
Button
Pure Javascript
This version without jQuert. Enjoy!
Note: There are some limitations on old browsers (IE < 8 && FF3.0)
// put your prices on an array;
var prices = [39.0, 59.0, 85.0];
var elements = document.querySelectorAll('[id^=widget]');
Array.prototype.forEach.call(elements, function(element) {
var index = parseInt(element.id.substring(7)) - 1;
var price = prices[index];
element.onclick = function(event) {
alert(price);
};
});
Button
Button
Button
Extract just the number
var r = /\d+/;
var s = "add_to_cart_sku_ThisItemA1_CEB";
var index = s.match(r);
alert (index);
Extract a substring (for instance "ItemA1")
var code = "add_to_cart_sku_ThisItemA1_CEB";
var strIndex = code.substring(code.indexOf("Item"), code.lastIndexOf('_'));
alert (strIndex);
if we can define the function :
function MatchID(id) {
var y = "0";
if (id == "widget_1") {
y = "39.00";
} else if (id == "widget_2") {
y = "59.00";
} else if (id == "widget_3") {
y = "85.00";
}
return y;
}
Button
use this
switch(document.getElementById(this.id)){
case "widget_1":
var value = "59.00";
break;
case "widget_2":
var value = "60.00";
break;
case "widget_3":
var value = "61.00";
break;
}
return value;
that is what you need to get the basic job done, now you just need to get the click to go there, if it is another page you will need to know how it was sent and how it is recieved
hope this helps.
document.getElementsByTagName should be given html tag name instead of id and than you can access its id attribute as document.getElementsByTagName("a")[i].id
your code should be as follow :
var num = [];
for (var i = 0; i<11; i++) {
num[i] = document.getElementsByTagName("a")[i].id;
if (num[i] == "widget_1"){ var y = "39.00"; return y;}
else if (num[i] == "widget_2"){ var y = "59.00"; return y;}
else if (num[i] == "widget_3"){ var y = "85.00"; return y;}
else { var y = "0";}
return y; }
document.getElementsByTagName("id") this line in your code is not correct because there's no tags in html that is called `.
To retrieve all of the <a> tags in your document, there's a property of the HTMLDocument interface which is referred to as the document object which represents the entire html document. To retrieve all of the <a> tags. use this.
document.links this method returns a collection of the <a> tags, you can access this collection just like you do an array. For example, to access the first child in that collection.
document.links[0].href to get its href value or to get its id, you do document.links[0].id . Hope this helps

How to get the parameter value from URL in Jquery?

Hi all i have an url where i need to get an parameter from the url
var URL="http://localhost:17775/Students/199/Kishore"
//here from the url i need to get the value 199
this is what i had been trying but the value is null here
function getURLParameter(name) {
return parent.decodeURI((parent.RegExp(name + /([^\/]+)(?=\.\w+$)/).exec(parent.location.href) || [, null])[1]);
};
$(document).ready(function() {
getURLParameter("Students");
//i need to get the value 199 from the url
});
jQuery is not needed for this, though it could be used. There are lots of ways to skin this cat. Something like this should get you started in the right direction:
var URL="http://localhost:17775/Students/199/Kishore";
var splitURL = URL.split("/");
var studentValue = "";
for(var i = 0; i < splitURL.length; i++) {
if(splitURL[i] == "Students") {
studentValue = splitURL[i + 1];
break;
}
}
Here's a working fiddle.
Edit
Based on the comments, indicating that the position will always be the same, the extraction is as simple as:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.split("/")[4];
This is what you're looking for since the URL parameter will keep changing:
http://jsbin.com/iliyut/2/
var URL="http://localhost:17775/Students/199/Kishore"
var number = getNumber('Students'); //199
var URL="http://localhost:17775/Teachers/234/Kumar"
var number = getNumber('Teachers'); //234
function getNumber(section) {
var re = new RegExp(section + "\/(.*)\/","gi");
var match = re.exec(URL);
return match[1];
}
I would do the following:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.match('/Students/(\\d+)/')[1]; //199

Categories

Resources