Javascript returning multiple checkbox values - javascript

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(', ');
}

Related

How to get groups a given user is a part of in SharePoint?

I'm trying to get the groups a given user (typed into a textbox in page) is a member of. Haven't had much success so decided to get all the groups, iterate through their users to find the groups the user is a part of. Tried the following but can't find a way to iterate through the users.
what am I missing? is there a better way to achieve my main goal?
var oGroupCollection, clientContext, loadedGroup, oUserCollection, oUser ;
function GetAllSiteGroups() {
// You can optionally specify the Site URL here to get the context
// If you don't specify the URL, the method will get the context of the current site
var clientContext = new SP.ClientContext("http://MyServer/sites/SiteCollection");
// Get Site Group Collection object
oGroupCollection = clientContext.get_web().get_siteGroups();
//oUserCollection = oGroupCollection.getByTitle('sp_red_dehn_zigaretten').get_users();
//console.log(oUserCollection);
// Load Site groups
clientContext.load(oGroupCollection);
// Execute the query to the server.
clientContext.executeQueryAsync(onsuccess, onfailed);
}
function onsuccess() {
// Iterate through each item
var oEnumerator = oGroupCollection.getEnumerator();
while (oEnumerator.moveNext()) {
var oGroup = oEnumerator.get_current();
console.log(oGroup);
console.log("Title of the group is: " + oGroup.get_title() + "\n");
oUserCollection = oGroup.get_users();
console.log(oUserCollection);
clientContext.load(oUserCollection);
clientContext.executeQueryAsync(onsuccess2, onfailed);
}
}
function onfailed(sender, args) {
console.log('Failed' + args.get_message() + '\n' + args.get_stackTrace());
}
function onsuccess2() {
// Iterate through each item
var oEnumerator = oUserCollection.getEnumerator();
while (oEnumerator.moveNext()) {
oUser = oEnumerator.get_current();
console.log(oUser);
//console.log("Title of the group is: " + oUser.get_title() + "\n");
}
}

How do I get the text() from a function to use in another function?

I'm trying to turn an option from a select list into text to then use the text in a function that returns a message topic for Firebase. I have had to use a function to get the text out of the list correctly but I don't know how to then output the text from the function in the second function to be used for the messaging. I can console.log the text, but I don't know what to use to just output the text itself inside the message function. I may be confusing myself a little. Please note: There are const being declared that are being used later on so any comment of "Why are you declaring those consts" won't be helpful. I need to know what to put in the TWO ### WHAT GOES HERE ### blocks to make this work?
I have tried just using jquery's text() to simply output the data I want but that just brings back undefined every time. The only way I've been able to actually get the option text is to place it in a function, but I have to actually DO something with it and I'm not sure what function will give me my desired results.
Here is the code
const select = $("#schoolSelect");
selectedOption = function() {
### WHAT GOES HERE? ###($("#schoolSelect option:selected").text())
}
const stage2 = $("#stage2Div");
const stage3 = $("#stage3Div");
const popupClose = $("#popupClose");
const popup = $("#popup");
const selectedValues = getSelectValues(select);
// Alert Buttons Functions
// Stage 2 Button
// Sends Soft Lockdown to all devices subscribed
stage2.click(function() {
var select = $("#schoolSelect"),
selectedValues = getSelectValues(select);
if (selectedValues.length == 0) {
popup.addClass("show");
}
else if (selectedValues.length > 0) {
for (var i = 0; i < selectedValues.length; i++) {
var message = createSLMessage(
"/topics/" + ### WHAT GOES HERE? ###
)
sendMessage(message);
}
}
});
For reference, here is the jQuery that is creating the list
populateList = function() {
$.getJSON("/assets/JSON/schools.JSON", function(result) {
$.each(result, function(i){
var schools = result.schools;
var output = "";
for (var i = 0; i < schools.length; i++) {
output += "<option>" + schools[i].topic + "</option>";
}
$("#schoolSelect").html(output);
});
})
};
Here is the html of the table (though less important) for reference
<select
size="100"
multiple
id="schoolSelect"
class="school_select"
></select>
I would like the function selectedOption to actually output the text. If I place console.log where the ### WHAT GOES HERE ### tag is in the function selectedOption itself and then call the selectedOption() later, the console indeed logs the correct value from the select list. I am losing my mind a little because I know there has to be some simple way to do this I just can't seem to figure it out.

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]

Removing whitespace in Javascript

Super newbie at Javascript here. I have a problem with whitespace that I'm hoping someone can help me with.
I have a function that looks like this:
function createLinks()
{
var i = 0;
tbody = document.getElementsByTagName('tbody')[3];
console.log('test order ID: '+document.getElementsByTagName('tbody')[3].getElementsByTagName('tr')[0].getElementsByTagName('td')[1].textContent.replace(/^\s+|\s+$/g,''))
trs = tbody.getElementsByTagName('tr');
console.log('trs.length = '+trs.length);
for (i=0;i<trs.length;i++)
{
orderId = trs[i].getElementsByTagName('td')[1].textContent.replace(/^\s+|\s+$/g,'');
console.log('order: '+orderId);
hrefReturn = 'https://www.example.com/example.html?view=search&range=all&orderId='+orderId+'+&x=13&y=17';
linkReturn = '<a href='+hrefReturn+'>'+orderId+'</a>';
console.log(linkReturn);
trs[i].getElementsByTagName('td')[1].innerHTML = linkReturn;
}
}
I call this function using another function when the page is initially loaded. This works perfectly.
However, I also call this function in another way when data on the page changes. There's a dropdown list that I have an onClick attribute attached to. That onClick event calls the first function, which in turn calls the second function (above). Both of these functions are saved into text variables and appended to the document, as below:
var scriptTextLinks = " function createLinksText() { var i = 0; tbody = document.getElementsByTagName('tbody')[3]; console.log('test order ID: '+document.getElementsByTagName('tbody')[3].getElementsByTagName('tr')[0].getElementsByTagName('td')[1].textContent.replace(/^\s+|\s+$/g,'')); trs = tbody.getElementsByTagName('tr'); console.log('trs.length = '+trs.length); for (i=0;i<trs.length;i++) { orderId = trs[i].getElementsByTagName('td')[1].textContent.replace(/^\s+|\s+$/g,'').replace(/\s/g,''); orderId = orderId.replace(/\s/g,''); console.log('order: '+orderId); hrefReturn = 'https://www.example.com/example.html?view=search&range=all&orderId='+orderId+'+&x=13&y=17'; linkReturn = '<a href='+hrefReturn+'>'+orderId+'</a>'; console.log(linkReturn); trs[i].getElementsByTagName('td')[1].innerHTML = linkReturn; } console.log('complete'); } "
Finally, here is the specific problem. When THIS version of the same function is called by events on the webpage, it fails to properly delete the whitespace, which breaks the link that it's supposed to create.
This is the exact problem section of code:
orderId = trs[i].getElementsByTagName('td')[1].textContent.replace(/^\s+|\s+$/g,'').replace(/\s/g,''); orderId = orderId.replace(/\s/g,''); console.log('order: '+orderId);
So instead of storing the variable like it should, like this:
"XXXXXXXXX"
It is stored like this:
"
XXXXXXXXXX
"
Which, again, kills the link.
Can anybody clarify what's going on here, and how I can fix it? Thanks in advance!
To strip all that surrounding whitespace you can use the standard .trim() method.
var myString = " \n XXXXXXX \n ";
myString = myString.trim();
You can strip all leading and trailing, and compress internal whitespace to a single space, as is normally done in HTML rendering, like this...
var myString = " \n XXXX \n YYYY \n ";
myString = myString.replace(/\s+/g, " ").trim();
Also, see tharrison's comment below.
(though my /\s+/g pattern worked fine with the embedded \n newlines)
Cure for IE<9
"shim.js"
(function() {
if (! String.prototype.trim) {
//alert("No 'trim()' method. Adding it.");
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/mg, '');
};
}
})();
(Or, if you might want to do other things in your shim...)
var shim = {
init: function() {
if (! String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/mg, '');
};
}
}
};
shim.init();
Your HTML file
<script type="text/javascript" src="shim.js"></script>

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

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.

Categories

Resources