Help modify a javascript - need to open link instead of displaying result - javascript

I'm trying to modify the code from this script. Basically I'm trying to get the script to send the browser to another page rather than display the results in a div.
This is the code in question:
<script type="text/javascript">
function openOneSlot() {
SpinningWheel.addSlot({1: 'First', 2: 'Second'});
SpinningWheel.setCancelAction(cancel);
SpinningWheel.setDoneAction(done);
SpinningWheel.open();
}
function done() {
var results = SpinningWheel.getSelectedValues();
document.getElementById('result').innerHTML = 'values: ' + results.values.join(' ') + '<br />keys: ' + results.keys.join(', ');
}
function cancel() {
document.getElementById('result').innerHTML = 'cancelled!';
}
window.addEventListener('load', function(){ setTimeout(function(){ window.scrollTo(0,0); }, 100); }, true);
</script>
I've changed the 'done' function to as follows:
function done() {
var results = SpinningWheel.getSelectedValues();
if (SpinningWheel.getSelectedValues() == "1,First")
{
window.location="first.html";
}
else if (SpinningWheel.getSelectedValues() == "2,Second")
{
window.location="second.html";
}
else
{
alert("Damn, Still not working..");
}
But now I'm lost as I'm very new to javascript.. Can anyone help the noob to get this working?
:)

Try this:
function done() {
var results = SpinningWheel.getSelectedValues();
if (results.values[0] == "First")
{
window.location.href="first.html";
}
else if (results.values[0] == "Second")
{
window.location.href="second.html";
}
else
{
alert("Damn, Still not working..");
}
The returned values appear to be an array of all the slots. Since yours has only one slot, I'm only looking at the first array position of the "results.values" array.

Try location.href instead of window.location
Note that this particular thing (changing page) is done differently across different browsers so you should google "javascript redirect " if you run into trouble on a particular browser

Look at what is returned by SpinningWheel.getSelectedValues(). It is an object with two properties keys and values. Therefore, it will not equal "1,First". Check into what is in those properties, and base your conditionals on those.

To pass your variables through, use the following syntax:
window.location = "first.html?var1Name=" + var1 + "&var2Name=" + var2;
To get the value of those variables on your first.html and second.html pages, you can use the window's query string to get hold of their values:
http://www.eggheadcafe.com/articles/20020107.asp
You would want to look at the window.location.search property.

Related

Javascript returning multiple checkbox values

I'm having some trouble trying to get multiple checkbox values. It currently is working, just not in the way I wanted/was hoping it would. Right now anything checked is appended to the bottom of the body and not inline with the function it was aiming to be inserted into.
I'm trying to avoid using JQuery or anything except JavaScript as it's all we've currently covered in our class.
function favMedia(media){
var media = document.forms['mediapref']['media'].value;
return media;
}
function pets(pet){
var pet = document.getElementsByName('pets')
for (var checkbox of pet){
if (checkbox.checked)
document.body.append(checkbox.value + ' ');
}
}
function about(text){
var info = document.forms['personal']['about'].value;
return info;
}
function infoForm(media, pet, text){
document.getElementById('infoset').innerHTML = favMedia(media) + "<br>" + pets(pet) + "<br>" + about(text);
}
Is there some way I can assign it just to a single variable to return and then throw into the last function?
Also please give me any tips or improvements on any aspect of the functions if you have any.
Put it in a string that you return from the function.
function pets(pet) {
var pet = document.querySelector('[name="pets":checked');
let selected = [...pet].map(p => p.value);
return selected.join(', ');
}

How to call JS-Functions only on HTML pages where they are being used and not on all of them?

I am creating a demo-website for a fictional company.
The most of it is written in Javascript but I have a problem that all my functions are getting called on every HTML-page, even if they are not getting used.
Example: I have a Contact page where only one function should be called, but right now all functions are being called. Those for my Booking page and so on.
I am trying to use window.addEventListener together with window.location.pathname without result.
function start() {
// variable for pathname. split in to substrings by '/'
var pathArray = window.location.pathname.split('/');
// check the last substring of the array for determening which script to
run
if(pathArray[pathArray.length-1] == "contact.html")
{
browserDetect();
}
else if(pathArray[pathArray.length-1] == "ourfleet.html")
{
showFirstFleetImg();
showFleetImg();
}
else if(pathArray[pathArray.length-1] == "employees.html")
{
showFirstStaffImg();
showStaffImg();
}
}
window.addEventListener("load", start, false);
One of the functions
function showFleetImg(arrayno) {
var fleethtml = "";
var caption = document.getElementById("planename");
for(var i = 0; i < fleetarray.length; i++) {
fleethtml = fleethtml + "<a href = '#' onclick = 'showFleetImg(" + i +
"); return false; '><img src='" + fleetarray[i] + "' /></a>";
}
fleetimage.src = fleetarray[arrayno];
caption.innerHTML = planename[arrayno];
document.getElementById("fleetthumbs").innerHTML= fleethtml;
}
function showFirstFleetImg(imgnum) {
showFleetImg(0);
}
window.addEventListener("load", showFirstFleetImg, false);
What more do I add, or how do I structure this right so function X is only called in HTML file Y?
It looks like you are looking for something like ES Modules. There is a lot of information here http://exploringjs.com/es6/ch_modules.html, but the gist is they encapsulation javascript code so that functions aren't executed right away.
If you rewrite your javascript file to something like
// foo.js
export function showFleetImg(arrayno) {
var fleethtml = "";
var caption = document.getElementById("planename");
for(var i = 0; i < fleetarray.length; i++) {
fleethtml = fleethtml + "<a href = '#' onclick = 'showFleetImg(" + i +
"); return false; '><img src='" + fleetarray[i] + "' /></a>";
}
fleetimage.src = fleetarray[arrayno];
caption.innerHTML = planename[arrayno];
document.getElementById("fleetthumbs").innerHTML= fleethtml;
}
export function showFirstFleetImg(imgnum) {
showFleetImg(0);
}
and then your other js file will look like
import {showFleetImg, showFirstFleetImg} from './foo.js'
function start() {
// variable for pathname. split in to substrings by '/'
var pathArray = window.location.pathname.split('/');
// check the last substring of the array for determening which script to
run
if(pathArray[pathArray.length-1] == "contact.html")
{
browserDetect();
}
else if(pathArray[pathArray.length-1] == "ourfleet.html")
{
showFirstFleetImg();
showFleetImg();
}
else if(pathArray[pathArray.length-1] == "employees.html")
{
showFirstStaffImg();
showStaffImg();
}
}
There is nothing in the code you've posted to suggest each function should first every time.
However, there are many better ways to do what you're trying to do.
Use separate JS files and call into each page only those that need to be executed
If you prefer to use one JS file like currently, don't conditionalise based on pathname; what if your filename changes? You'd have to update your JS each time.
As regards the latter point, it would make more sense to act on the presence (or lack thereof) of a data attribute on the body identifying which page is currently showing.
HTML
<body data-page='contact'>
JS
switch (document.body.getAttribute('data-page')) {
case 'contact': /* do something */ break;
case 'fleet': /* do something else */ break;
//etc...
}
Note also the use of switch() rather than duplicative if/else if statements.
[Edit - or have a look at Modules as per #user1816294's answer]

use javascript to find parameter in url and then apply if then logic

I am trying to make my page perform an action only if it sees that a particular parameter is present in the url.
I essentially want the javascript code to do this:
consider an example page such as: http://www.example.com?track=yes
If a page loads that contains the parameter 'track' within the url, print 'track exists', else if the 'track' parameter doesn't exist print 'track does not exist'
This should work:
if (window.location.search.indexOf('track=yes') > -1) {
alert('track present');
} else {
alert('track not here');
}
Use something like the function from Artem's answer in this SO post:
if (getParameterByName('track') != '') {
alert ('run track');
}
It's not hard to split up the query string to find the relevant bits:
var path = location.substr(1), // remove ?
queryBits = path.split('&'),
parameters = {},
i;
for (i = 0 ; i < queryBits.length ; i++) {
(function() { // restrict keyval to a small scope, don't need it elsewhere
var keyval = queryBits[i].split('=');
parameters[decodeURIComponent(keyval[0])] = decodeURIComponent(keyval[1]);
}());
}
// parameters now holds all the parts of the URL as key-value pairs
if (parameters.track == 'yes') {
alert ('track exists');
} else {
alert ("it doesn't");
}
What you're looking for is called the Query String or Query Parameter. See this function to get it w/o the use of plugins like jQuery: How can I get query string values in JavaScript?
You can use the window.location.search property:
if(/(^|&)track(&|$)/.test(window.location.search.substring(1))) {
alert('track exists!');
} else {
alert('it doesn\'t...');
}

Javascript Variable Scope Confusion

In the following code snippet I've declared the variable "id" within the submit function. I attempt to assign a value to it within a nested function but it doesn't appear to be within scope and I don't know why.
$(document).ready(function() {
if (typeof(localStorage) == 'undefined' ) {
alert('Your browser does not support HTML5 localStorage. Try upgrading.');
}
else {
$("#logForm").submit(function(){
var id;
chrome.bookmarks.getRecent(1, function(mostrecent) {
getLastId(mostrecent);
});
function getLastId(mostrecent) {
mostrecent.forEach(function(mostrecent) {
lastId = mostrecent.id;
alert(lastId + ' was last id');
id = lastId;
})
}
alert(id + ' outside function');
Bonus Question - If you know a better way to pull the last-used id from chrome for a bookmark would love to know what it is. I had to pull recent which doesn't account for the possibility of an added and then deleted last bookmark which would have incremented the index.
This should do it:
$("#logForm").submit(function() {
var id;
chrome.bookmarks.getRecent(1, function(arr) {
id = arr.pop().id;
});
// do stuff with id
});

How to carry "getjson" functionality from one func to another?

Basically I have a getjson call to call for a bunch load of data. Now I am getting sick of the amount of if data is null else checks.
For Example:
if (data.Height == "") {
$('#DataHeight').html('No Data is Available');
}
else {
$('#DataHeight').html(data.Height);
}
Reason being is the user has to be alerted asap that data is not available.
So I went off and am trying to write a DataCheck.js to include and handle all this outside of my pretty little page :D.
Function:
function DataNullCheck(ObjectName) {
if (data.ObjectName == "") {
$('"#Data' + ObjectName + '"').html('No Datablurgh');
}
else {
$('"#Data' + ObjectName + '"').html(data.ObjectName);
}
}
and to call it inside my function
function getdata() {
$.ajaxSetup({
cache: false
});
$.getJSON(urldefault, function (data) {
DataNullCheck('Height');
.......
And Data is undefined. Because it is not within the JSON call?
Any help or hints towards the right direction would be appreciated especially an explanation of why it works one way or another. Thanks in advance.
How would I carry through the getJson call functionality to my little function?
Pass data as a parameter to your function:
function DataNullCheck(data, ObjectName) { // you can check for null any property of data
// e.g. DataNullcheck(data, "Width"), or
// DataNullCheck(data, "Height") etc.
if (!data[ObjectName]) {
$('"#Data' + ObjectName + '"').html('No Datablurgh');
}
else {
$('"#Data' + ObjectName + '"').html(data.ObjectName);
}
}

Categories

Resources