r/JavaScriptHelp • • Nov 07 '18

Using a variable for multidimensional arrays

1 Upvotes

Please keep in mind I am NOT a javascripter. Javascript is difficult for me to understand, but I am trying.

I have this webform that HR uses on our intranet server.

I made it so HR can quickly add in new hires. The submissions are fed into a sql database, where I have an automated script take care of all the repetitive tasks (ie. add to Active Directory, assign licenses, phone numbers, etc)

HR asked me to add in a field for distribution groups. Some new hires need to be put into select email lists and it's not always consistent, so scripting it would be difficult.

The site can add more than one row of all these fields (First name, last name, title, department, notes, etc) in the event there is more than one hire. Clicking submit sends all that stuff into my sql server. This is done by javascript. For brevity, the html variable is cut down to what i need fixed:

$(document).ready(function() {


var html = '<div class="cell" align="justify"><select name="emaillist[???][]" id="emaillist" style="width:200px; padding: 5px; vertical-align: -38px;" size="3" 
multiple><option value="b792a010-f6d1-47ff-a43b-775e71220142">A&A Managers</option><option value="85d59de6-2924-4741-ac70-7b0a9894ba32">A&A 
Partners</option><option value="dd177d82-6d5c-4279-820f-4ca0b0309b1d">A&A Staff</option><option value="b91d4aba-7fe4-4d6d-96b5- 
fc539c1216d1">BEST</option></select></div><div class="cell" align="center"><input type="text" name=notes[]" size="20" id="notes" 
style="width:350px"></div><div class="cell" align="center" style="width:39px"><input class="redbutton" type="button" id="remove" value=" - "></div> 
 </div></div>';


$("#add").click(function(e) {
    $("#added_fields").append(html);
});

$("#added_fields").on("click","#remove",function(e) {
    $(this).parent().parent().parent().remove();
});
});

The html field is this:

<select name="emaillist[0][]" id="emaillist" style="width:200px; padding: 5px" size="1" multiple>
            <option value="b792a010-f6d1-47ff-a43b-775e712">A&A Managers</option>
            <option value="85d59de6-2924-4741-ac70-7b0a989">A&A Partners</option>
            <option value="dd177d82-6d5c-4279-820f-4ca0b03">A&A Staff</option>
            <option value="b91d4aba-7fe4-4d6d-96b5-fc539c12">BEST</option>
        </select></div>

The results get fed into sql. This all works fine and dandy if manually declare the array with numbers eg: emaillist[0][]; emaillist[1][], etc

but since HR can dynamically add or remove rows; is there a way I can input a variable when I add another column?

so it can be something like this:

var html = '<div class="cell" align="justify"><select name="emaillist[$X+1][]" id="emaillist" style="width:200px; padding: 5 etc...

where $x is a variable that starts at 0 and keeps a counter? I can do something like this in bash or powershell but javascript has me at so many losses.


r/JavaScriptHelp • • Oct 31 '18

localStorage JavaScript

1 Upvotes

I am trying to create a quiz using localStorage and let the user be able to retrieve the quiz made so that they will be able to take the quiz. I am stuck on how to show the results of the quiz which must include the grade earned on the quiz, the answers entered by the user and whether the question answered was correct or incorrect and the correct answers. I am stuck on how to retrieve the answers.

Here's a link to my github.

function nextQue(){

if (getQuestion[i] == null) {

//get answers and scores

}

else {

queNo.innerText="Question No "+ getQuestion[i].qId;

question.innerText=getQuestion[i].quest;

if(getQuestion[i].qType==="multi"){

forMulti.style.display="block";

forRad.style.display="none";

forShort.style.display="none";

lblCheckBox1.innerHTML=" "+getQuestion[i].choice1;

lblCheckBox2.innerHTML=" "+getQuestion[i].choice2;

lblCheckBox3.innerHTML=" "+getQuestion[i].choice3;

lblCheckBox4.innerHTML=" "+getQuestion[i].correctAnswer;

chkBox1.value=getQuestion[i].choice1;

chkBox2.value=getQuestion[i].choice2;

chkBox3.value=getQuestion[i].choice3;

chkBox4.value=getQuestion[i].correctAnswer;

i++;

}

else if(getQuestion[i].qType==="radio"){

forMulti.style.display="none";

forRad.style.display="block";

forShort.style.display="none";

i++;

}

else if(getQuestion[i].qType==="short"){

forMulti.style.display="none";

forRad.style.display="none";

forShort.style.display="block";

i++;

}

}

}


r/JavaScriptHelp • • Mar 09 '18

help with a price calculator

1 Upvotes

Hi i wrote a code for a price calculator where you are supposed to enter you price state residence etc on a pop-up prompt, but i dont know how to get the pop up to work or how to display my final sum any help tonight would be greatly appreciated https://paste.ofcode.org/hnEBQHENPyz6dMkUmiguQE


r/JavaScriptHelp • • Mar 03 '18

Fetch Put in React

1 Upvotes

I have amended my fetch request as I would like to be able to update the contents of my MySQL database once this component is called.

When the component is called I can see in the terminal the put request going through to the server (the request is submitted around 30 times!) however the data within "body" is not passed through.

 import React, { Component } from 'react';

 const actionUrl = (id) => `http://localhost:3001/jobs/${id}`

 export class JobClaim extends Component {
 constructor(props){
   super(props)
 this.state = {
  response: []
   }
 }

 claimJob() {
    fetch(actionUrl(this.props.id), {
     method: 'PUT',
    body: {
    "data_name": "test nane",
    "data_details": "test details",
 })
 .then(response => { if (!response.ok)
   { throw Error("Network request failed") }

  return response;
  })
  .then(jobs => jobs.json())
  .then(jobs => {
  this.setState({
  response: jobs
  })
  }, () => {
  this.setState({
    requestFailed: true
  })
  })
}

 render() {
if(this.props.status === 'available') {
{this.claimJob()}
return (<div>
<div>Job Claimed</div>
</div>)

} else { return ( <div> <div>taken</div> </div> ) }

     }
   }

r/JavaScriptHelp • • Oct 10 '17

Need help with do/while loops.. *javascript*

1 Upvotes

I need to write a do..while loop that builds a string with multiple inputs from a user. Start by prompting the user if they want to play. When the user answers yes, prompt the user to enter a word. After the user enters a word, prompt the user if they would like to play again. If no, console log their word. If yes, prompt the user for another word and add that word to the original string, then prompt if they want to play again. Continue to add words to the string every time the user answers yes and enters a word until the user indicates that he or she does not want to play anymore.


r/JavaScriptHelp • • Feb 26 '18

Table Pagination Help

1 Upvotes

How can I paginate this table? Thanks!

<table id="datatable">
	<thead>
		<tr>
			<th>Agency</th>
			<th>Site</th>
			<th>Town</th>
			<th>Acres</th>
			<th>Trail Style</th>
			<th>Dogs</th>
			<th>Stroller Score</th>
			<th>Water</th>
		</tr>
	</thead>
	<tbody>
	</tbody>
</table>

<script>
var table = document.getElementById('datatable').tBodies[0];

while (table.firstChild) {
	table.removeChild(table.firstChild);
}
function getValues(data) {
	var raw = data.split(',');
	var values = {};

	raw.map((value) => {
		var i = value.indexOf(':');
		if (i !== -1) {
			var arr = [value.slice(0,i), value.slice(i+1)];
			Object.assign(values, {[arr[0].trim()]: arr[1]});
		}
	});

	return values;
}

function fillTable(data) {
	var values = [];
	data.map((entry) => {
		var row = getValues(entry.content.$t);

		values.push({
			agency: row.agency || "",
			site: entry["gsx$link"]["$t"].includes('http') ? '<a href="'+entry.gsx$link.$t+'">'+row.site+'</a>' : row.site || "",
			town:entry["gsx$link"]["$t"].includes('http') ? '<a href="'+entry.gsx$link.$t+'">'+row.town+'</a>' : row.town || "",
			acres: row.acres || "",
			outback: row.outback || "",
			dogs: row.dogs || "",
			stroller: row.stroller || "",
			water: entry["gsx$water"]["$t"] !== "" ? entry["gsx$water"]["$t"] : row.water || ""
		});
	});

	jQuery('#datatable').dataTable({
		"data": values,
		"destroy": true,
				"paging": false,
		"columns": [
			{ "data": "agency" },
			{ "data": "site" },
			{ "data": "town" },
			{ "data": "acres" },
			{ "data": "outback" },
			{ "data": "dogs" },
			{ "data": "stroller" },
			{ "data": "water" }
		]
	});
}

function getTable() {
	var url = 'https://spreadsheets.google.com/feeds/list/1bv-5DiFTT5rSTagKvvcB-ImnUuOsihq8mKhyEW2dOVs/od6/public/values?alt=json';
	var req = new XMLHttpRequest();	

	req.onreadystatechange = function() {
		if (req.readyState === 4) {
			var json = JSON.parse(req.responseText).feed;
			fillTable(json.entry);
		}
	};

	req.open("GET", url, true);
	req.send();
}

jQuery('#datatable').ready(() => { getTable(); });
</script>

r/JavaScriptHelp • • Oct 03 '17

Help with a noob's JavaScript code for D&D 5e (Cross posted to (r/DnD)

1 Upvotes

Hello there, I'm using an automated character sheet for D&D 5e created by morepurplemorebetter that supports adding homebrew content with the provided syntax.

I've been trying to adapt the Dark Arts Player's Companion to work with this code, but I'm basically learning as I go.

I have reached out to the creator of the sheet, but they are too busy to assist me and trouble shoot my code. So far I have followed the syntax as best as I can, but I get the following error messages.

Would anyone be willing to assist me in troubleshooting my code? My current progress is located here. Any help would be appreciated.


r/JavaScriptHelp • • Oct 16 '21

❔ Unanswered ❔ What Java script IDE

1 Upvotes

I'm new to JavaScript having previously only coded in python and I was wondering what are the best free java script IDEs


r/JavaScriptHelp • • Nov 04 '21

❔ Unanswered ❔ (New to JS) Help With Delaying a Script

2 Upvotes

Hi,

I've been tasked with adding the below script to a clients website to load an online booking widget, however it's absolutely tanking the page load speed.

I was hoping there is a way to stop the script loading until a button is clicked, or at least delay the loading of the script to allow the page to load.

<script type='text/javascript'>!function(b,c){b.saloniqid='119423d7-1209-4ee5-8e1b-f8a71f0b7345',b.saloniqsite='https://bookings.saloniq.co.uk';var d,g,e='onlinebookingwidget-loader',f=c.getElementsByTagName('script')[0];c.getElementById(e)||(d=c.createElement('script'),d.id=e,d.async=!0,d.src=b.saloniqsite+'/scripts/onlinebookingwidget-loader.js?d='+Date.now(),g=f?f.parentNode:c.getElementsByTagName('head')[0],g.insertBefore(d,f))}(window,document);</script>

Thanks!


r/JavaScriptHelp • • Oct 18 '21

✔️ answered ✔️ Dividing a number, then display that result in a form field

1 Upvotes

The form I'd like to modify populates this field (balance amount) upon the page appearing:

<div class="col-md-10">
<input type="text" readonly="true" class="form-control input-md" type="number" placeholder="00" value="{{balance}}">  
</div>

I'd like to divide that balance amount by 2, and have that result display in it's own seperate form field.

Any help with this is appreciated.


r/JavaScriptHelp • • Nov 11 '21

❔ Unanswered ❔ Silly error that I can't work out : variable is undefined

2 Upvotes

Hi,

I'm making a game where you have to click on svg boxes of a certain colour. Anyway, after some changes I have an error that I can't work out:

Uncaught TypeError: current_elem is undefined

current_elem is defined on this line

var current_elem=document.getElementById("rect-red");

, why is my code not seeing it?

I haven't tidied up my code for my question, I think it will be a dumb mistake and it will be clear anyway.

Thanks a lot.

Full html /css/js

https://pastebin.com/LHE5HySF

!DOCTYPE html>

<html>

<head>

`<title>Javascript + DOM</title>`

<meta charset="utf-8">

`<style>`

body{color: pink;background-color: black;font-size:1.2em;}

div{border: 2px solid pink;}

#container {

display: grid;

grid-gap: 20px;

grid-template-rows: 1fr;

grid-template-columns: 1fr 1fr;

justify-items: end;

align-items: end;

}

#rect-red{

fill: red;

stroke-width: 3;

stroke: black;

}

#rect-green{

fill: green;

stroke-width: 3;

stroke: black;

}

#rect-blue{

fill: blue;

stroke-width: 3;

stroke: black;

}

#rect-orange{

fill: orange;

stroke-width: 3;

stroke: black;

}

svg {

background-color: dimgrey;

/*border: 2px solid pink;*/

/*display: inline-block;*/

padding : 5px ;

/*top-bottom left-right*/

margin : 10px ;

}

</style>

</head>

<body>

<div id="container">

<div id="boxes">

<svg id='boxes' x='500' height="300" width="300" viewPort="0 0 300 300" >

<g transform="scale(2.0)">

<rect class='rect' id='rect-red' x="10" y="10" width="60" height="60" rx="15" ry="15" />

<rect class='rect' id='rect-green' x="80" y="10" width="60" height="60" rx="15" ry="15" />

<rect class='rect' id='rect-blue' x="10" y="80" width="60" height="60" rx="15" ry="15" />

<rect class='rect' id='rect-orange' x="80" y="80" width="60" height="60" rx="15" ry="15" />

</g>

</svg>

</div>

<div id="instruction-box">

<br>

<button onclick="question()"> START </button>

</div>

<div id="message-box">

<br>

Messages

</div>

</div>

</body>

<script type="text/javascript">

var svg_rectangles= document.getElementsByClassName('rect');

//svg_rectangles is not an array. It is HTMLCollection and it does not have //forEach method. You must convert it to an array first:

var svg_elements = Array.prototype.slice.call(svg_rectangles);

svg_elements.forEach(makeClickEvent);

//var stateArray=0;

var stateArray=initialiseStateArray(svg_elements);

function initialiseStateArray(svg_elements) {

//LIST (old way)

// var StateArray = [];

//DICT

var stateArray = {};

svg_elements.forEach(addToStateArray);

function addToStateArray(current_elem) {

//LIST (old way)

//stateArray.push([current_elem,false])

//false is unclicked

//DICT

stateArray[current_elem.id]=false;

}

console.log('STATE ARRAY INITIALISED')

console.log(stateArray)

return stateArray

}

var current_elem=document.getElementById("rect-red");

function setState(current_elem,state) {

stateArray[current_elem.id]=state;

console.log('STATE ARRAY VALUE SET');

string=' '+current_elem.id + ' > ' +state

console.log(string);

console.log(stateArray);

return stateArray;

}

setState(current_elem,true);

function resetStateArray(stateArray) {

for(var key in stateArray) {

stateArray[key]=false;

}

console.log('STATE ARRAY RESET');

console.log(stateArray);

return stateArray;

}

stateArray=resetstateArray(stateArray);

function makeClickEvent(current_elem) {

current_elem.addEventListener("click", outputMessage);

stateArray=updateClickedStatus(stateArray,current_elem);

function outputMessage(current_elem) {

var output = document.getElementById("message-box");

rect_name=event.target.id

message= rect_name + " clicked!"

output.textContent = message;

//update the state, set all to false then set the one that has been clicked to true

}

function updateClickedStatus(current_elem) {

setState(current_elem,true)

}

}

function question() {

//get a box

current_elem=svg_elements[0] ;

//print the instruction

var instruction = document.getElementById("instruction-box");

var box = document.getElementById("rect-orange");

rect_name=event.target.id

message= "Click on "+box.id

instruction.textContent = message;

//reset svg_state_array

}

</script>

</html>


r/JavaScriptHelp • • Sep 29 '21

❔ Unanswered ❔ Beginner to JavaScrip - help needed!

1 Upvotes

In the link below, I have a task I am trying to complete and thought I had written the syntax correctly to answer all of the criteria in the task but after I press enter with the pop ups (alerts) for the users input the output is not displayed onto the webpage and I don’t know what I have done wrong, if anyone knows how to fix it I would really appreciate the help!

https://imgur.com/gallery/ZlBc5PL


r/JavaScriptHelp • • Oct 22 '21

❔ Unanswered ❔ How do I solve this uncaught reference error: like_post is not defined at HTMLAnchorElement.onclick?

1 Upvotes

I recently live hosted my website and got this error. Uncaught ReferenceError: like_post is not defined at HTMLAnchorElement.onclick

This error did not occur on the local server but it occurred on a public server. I saw a few threads regarding this error and I heard that you should use addEventListener instead of onclick in your code. However, I'm not sure how to implement it into my code so it would be great if you could help me.

This is the line where the error occurred:

<a onclick="like_post(event)" href="<?= ROOT ?>like/post/<?php echo $ROW['postid'] ?>" style="text-decoration:none;float:left;position:relative;top:2px;">
				<svg id="icon_like" fill="<?= $Like_color ?>" width="22" height="22" viewBox="0 0 24 24">
					<path d="M21.216 8h-2.216v-1.75l1-3.095v-3.155h-5.246c-2.158 6.369-4.252 9.992-6.754 10v-1h-8v13h8v-1h2l2.507 2h8.461l3.032-2.926v-10.261l-2.784-1.813zm.784 11.225l-1.839 1.775h-6.954l-2.507-2h-2.7v-7c3.781 0 6.727-5.674 8.189-10h1.811v.791l-1 3.095v4.114h3.623l1.377.897v8.328z" />
				</svg>
			</a>

This is the JS:

<script type="text/javascript">
     window.onload = function() {
        function ajax_send(data, element) {

            var ajax = new XMLHttpRequest();

            ajax.addEventListener('readystatechange', function() {

                if (ajax.readyState == 4 && ajax.status == 200) {

                    response(ajax.responseText, element);
                }

            });

            data = JSON.stringify(data);

            ajax.open("post", "<?= ROOT ?>ajax.php", true);
            ajax.send(data);

        }
     
        function response(result, element) {

            if (result != "") {

                var obj = JSON.parse(result);
                if (typeof obj.action != 'undefined') {

                    if (obj.action == 'like_post') {

                        var likes = "";

                        if (typeof obj.likes != 'undefined') {
                            likes =
                                (parseInt(obj.likes) > 0) ?
                                '<svg fill="#1877f2" width="22" height="22" viewBox="0 0 24 24"><path d="M21.216 8h-2.216v-1.75l1-3.095v-3.155h-5.246c-2.158 6.369-4.252 9.992-6.754 10v-1h-8v13h8v-1h2l2.507 2h8.461l3.032-2.926v-10.261l-2.784-1.813zm.784 11.225l-1.839 1.775h-6.954l-2.507-2h-2.7v-7c3.781 0 6.727-5.674 8.189-10h1.811v.791l-1 3.095v4.114h3.623l1.377.897v8.328z"/></svg>' :
                                '<svg fill="#626a70cf" width="22" height="22" viewBox="0 0 24 24"><path d="M21.216 8h-2.216v-1.75l1-3.095v-3.155h-5.246c-2.158 6.369-4.252 9.992-6.754 10v-1h-8v13h8v-1h2l2.507 2h8.461l3.032-2.926v-10.261l-2.784-1.813zm.784 11.225l-1.839 1.775h-6.954l-2.507-2h-2.7v-7c3.781 0 6.727-5.674 8.189-10h1.811v.791l-1 3.095v4.114h3.623l1.377.897v8.328z"/></svg>';
                            element.innerHTML = likes;
                        }

                        if (typeof obj.info != 'undefined') {
                            var info_element = document.getElementById(obj.id);
                            info_element.innerHTML = obj.info;
                        }
                    }
                }
            }
        }
     
        function like_post(e) {

            e.preventDefault();
            var link = e.currentTarget.href;

            var data = {};
            data.link = link;
            data.action = "like_post";
            ajax_send(data, e.currentTarget);
        }
     }
     
    </script>

r/JavaScriptHelp • • Oct 23 '21

💡 Advice 💡 how to handle Insert multi rows query when is duplicate or violates foreign key

2 Upvotes

I'm using nodejs, express, postgres as sql server. I created Javascript API that sends queries to the server, And i want when i send a multi-line insert query to the server if one or more of the lines already in the system the query will continue without those in the server And if foreign key error happen(is not present in table "tablename") it will ask the client(wait for response) if to add it to the foreign table and then continue with the query.

So far i did this code, but can not figure out where to start with this problem:

    insert(){
    	return new Promise( async (resolve, reject) => {
    		const client = await this.PoolCONN.connect();
    
    		client.query(query, (err, results)=>{
    			
    			if(err){
    				const error = this.HandlError(err)
    				client.release();
    				return reject(error);
    			};
    			
    			client.release();
    			return resolve(results);
    
    		});
        })
    }

    HandlError(error){
	const ErrorCode = error.code;
	let errorName = "";
	let msg = "";
	switch (ErrorCode) {
		case '23505': // duplicate values
			
			msg = ``;
			errorName = "duplicate";
			break;                
		case '23503': // foreign_key_violation
			msg = ``
			errorName = "foreign key"
			break;                
		default:
			break;
	}

	return {
		error: errorName,
		errorMSG: msg,
	}
    }

NOTE: I know I'm asking for a lot I'm a bit lost


r/JavaScriptHelp • • Oct 22 '21

❔ Unanswered ❔ Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')

1 Upvotes

I recently live hosted my website and got this error. Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')

This error did not occur on the local server but it occurred on a public server.

This is the line where the error occurred:

<a onclick="like_post(event)" href="<?= ROOT ?>like/post/<?php echo $ROW['postid'] ?>" style="text-decoration:none;float:left;position:relative;top:2px;">
				<svg id="icon_like" fill="<?= $Like_color ?>" width="22" height="22" viewBox="0 0 24 24">
					<path d="M21.216 8h-2.216v-1.75l1-3.095v-3.155h-5.246c-2.158 6.369-4.252 9.992-6.754 10v-1h-8v13h8v-1h2l2.507 2h8.461l3.032-2.926v-10.261l-2.784-1.813zm.784 11.225l-1.839 1.775h-6.954l-2.507-2h-2.7v-7c3.781 0 6.727-5.674 8.189-10h1.811v.791l-1 3.095v4.114h3.623l1.377.897v8.328z" />
				</svg>
			</a>

This is the JS:

<script type="text/javascript">
		function ajax_send(data, element) {

			var ajax = new XMLHttpRequest();

			ajax.addEventListener('readystatechange', function() {

				if (ajax.readyState == 4 && ajax.status == 200) {

					response(ajax.responseText, element);
				}

			});

			data = JSON.stringify(data);

			ajax.open("post", "<?= ROOT ?>ajax.php", true);
			ajax.send(data);

		}

		function response(result, element) {

			if (result != "") {

				var obj = JSON.parse(result);
				if (typeof obj.action != 'undefined') {

					if (obj.action == 'like_post') {

						var likes = "";

						if (typeof obj.likes != 'undefined') {
							likes =
								(parseInt(obj.likes) > 0) ?
								'<svg fill="#1877f2" width="22" height="22" viewBox="0 0 24 24"><path d="M21.216 8h-2.216v-1.75l1-3.095v-3.155h-5.246c-2.158 6.369-4.252 9.992-6.754 10v-1h-8v13h8v-1h2l2.507 2h8.461l3.032-2.926v-10.261l-2.784-1.813zm.784 11.225l-1.839 1.775h-6.954l-2.507-2h-2.7v-7c3.781 0 6.727-5.674 8.189-10h1.811v.791l-1 3.095v4.114h3.623l1.377.897v8.328z"/></svg>' :
								'<svg fill="#626a70cf" width="22" height="22" viewBox="0 0 24 24"><path d="M21.216 8h-2.216v-1.75l1-3.095v-3.155h-5.246c-2.158 6.369-4.252 9.992-6.754 10v-1h-8v13h8v-1h2l2.507 2h8.461l3.032-2.926v-10.261l-2.784-1.813zm.784 11.225l-1.839 1.775h-6.954l-2.507-2h-2.7v-7c3.781 0 6.727-5.674 8.189-10h1.811v.791l-1 3.095v4.114h3.623l1.377.897v8.328z"/></svg>';
							element.innerHTML = likes;
						}

						if (typeof obj.info != 'undefined') {
							var info_element = document.getElementById(obj.id);
							info_element.innerHTML = obj.info;
						}
					}
				}
			}
		}

		function like_post(e) {

			e.preventDefault();
			var link = e.currentTarget.href;

			var data = {};
			data.link = link;
			data.action = "like_post";
			ajax_send(data, e.currentTarget);
		}
	</script>

r/JavaScriptHelp • • Nov 12 '21

❔ Unanswered ❔ different output from when I first run page to when I refresh page (callback /timing related?)

2 Upvotes

I'm learning about callbacks and have noticed a problem. There are no callbacks in this particular code but I think there is something to do with timing.

When I run my code for the first time, the console output after I call getUsers1() should give this:

Array(6) [ "Sam", "Ellie", "Toady", "Jake", ]

But it outputs this:

Array(6) [ "Sam", "Ellie", "Toady", "Jake", "Jake1", "Jake2" ]

If I refresh the browser, it works as intended. What's going on?

Thanks!

PS how do I change flair (browser version)? I see nothing in the edit post options.

Here is my code:

<meta charset='utf-8'>

<script>

var users = ["Sam", "Ellie","Toady"]

function addUser(username){

`users.push(username);`

};

function getUsers1(){

`console.log(users);`

}

addUser('Jake');

getUsers1(); //FIRST LINE OF CONSOLE OUTPUT

s=addUser('Jake1');

console.log(s)

function getUsers2(){

`console.log(users);return users;`

}

t=addUser('Jake2');

t=getUsers2();

console.log(t)

</script>


r/JavaScriptHelp • • Oct 20 '21

✔️ answered ✔️ Help with getting share-video info to appear

1 Upvotes

This code works on another page, but I’m trying to move it (use it) on a new page. I believe I have copied all that is needed, but it does not display the share-video form. I don’t know a lot about javascript so, I thought I’d start here.

$(function () {
$('#share-video').on('click', function(event) {
      event.preventDefault();
      $('.share-video').toggleClass('hidden');
   });

<div>
<button class="btn-share" id="share-video"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="currentColor" d="M18,16.08C17.24,16.08 16.56,16.38 16.04,16.85L8.91,12.7C8.96,12.47 9,12.24 9,12C9,11.76 8.96,11.53 8.91,11.3L15.96,7.19C16.5,7.69 17.21,8 18,8A3,3 0 0,0 21,5A3,3 0 0,0 18,2A3,3 0 0,0 15,5C15,5.24 15.04,5.47 15.09,5.7L8.04,9.81C7.5,9.31 6.79,9 6,9A3,3 0 0,0 3,12A3,3 0 0,0 6,15C6.79,15 7.5,14.69 8.04,14.19L15.16,18.34C15.11,18.55 15.08,18.77 15.08,19C15.08,20.61 16.39,21.91 18,21.91C19.61,21.91 20.92,20.61 20.92,19A2.92,2.92 0 0,0 18,16.08Z" /></svg> {{LANG share}}</button>
</div>
		  <div class="share-video hidden">
               	  <div class="row share-input">
<div class="col-md-4">
<input type="text" value="{{CONFIG site_url}}/v/<?php echo $pt->get_video->short_id; ?>" class="form-control input-md" readonly onClick="this.select();">
                  </div>
                  </div>
               <a href="#" class="fa fa-facebook" onclick="OpenShareWindow('https://www.facebook.com/sharer/sharer.php?u={{ENCODED_URL}}')"></a>
               <a href="#" class="fa fa-twitter" onclick="OpenShareWindow('https://twitter.com/intent/tweet?url={{ENCODED_URL}}')"></a>
               <a href="#" class="fa fa-google" onclick="OpenShareWindow('https://plus.google.com/share?url={{ENCODED_URL}}')"></a>
               <a href="#" class="fa fa-linkedin" onclick="OpenShareWindow('https://www.linkedin.com/shareArticle?mini=true&url={{ENCODED_URL}}&title={{TITLE}}')"></a>
               <a href="#" class="fa fa-pinterest" onclick="OpenShareWindow('https://pinterest.com/pin/create/button/?url={{ENCODED_URL}}&media={{THUMBNAIL}}')"></a>
               <a href="#" class="fa fa-tumblr" onclick="OpenShareWindow('http://www.tumblr.com/share/link?url={{ENCODED_URL}}')"></a>
               <a href="#" class="fa fa-reddit" onclick="OpenShareWindow('http://www.reddit.com/submit?url={{ENCODED_URL}}')"></a>
               <a href="#" onclick="copyToClipboard(this)" class="fa fa-link" link="{{CONFIG site_url}}/v/<?php echo $pt->get_video->short_id; ?>"></a>
            </div>

Can you make a suggestion as to what I might be missing to get the share links to appear/display?

any help is appreciated


r/JavaScriptHelp • • Jun 13 '18

Converting pure JS to JQuery

1 Upvotes

Here is the Fiddle

Here is what I have already and it’s not working and I’m stuck:

checkboxes = document.getElementsByName('aliases[]');
$(document).ready(function() {
 $("#domain").change(function() {
	$(checkboxes).each( function( index, element ){
       if ($(this).val() == $(sel).value) {
			$(this).prop("disabled", true);
		} else {
			$(this).prop("disabled", false);
		}
   });
 });
});

r/JavaScriptHelp • • Jun 14 '18

javascript API response problem

1 Upvotes
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
//create API REQUEST
var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function(){

//CHECKING STATUS CODE
if(this.readyState == 4 && this.status == 200){

//PARSING JSON DATA
var data = JSON.parse(this.responseText);

//LOOPING THROUGH DATA
for(var key in data){

//add the looped items to variable
var items = data[key];

var tablerow = document.createElement("tr");
var tabledetail1 = document.createElement("td");
var tabledetail2 = document.createElement("td");
var tabledetail3 = document.createElement("td");

// add CSS id to tabe row
tablerow.id = 'tablerow';

// add CSS id to tabledetail
tabledetail1.id='tabledetail1';

//get image url from object
var imgurl = items.image.small;

//create image element
var img = document.createElement('img');

//inject url into img src
img.src = imgurl;

//add id for styling
img.id ='img';

//add detail to row
tablerow.appendChild(tabledetail1);
tablerow.appendChild(tabledetail2);
tablerow.appendChild(tabledetail3);

//add img to table detail
tabledetail1.appendChild(img);

//get all coin id's
var id = document.createTextNode(items.id);

//append id to table detail
tabledetail2.appendChild(id);

//get price
var price = document.createTextNode(items.market_data.current_price.btc);

//apply price to tableheading1
tabledetail3.appendChild(price);

//append table row to table in document
document.getElementById('box').appendChild(tablerow);

}

}

}

//DEFINING GET REQUEST WITH URL
xhr.open('GET','https://api.coingecko.com/api/v3/coins?per_page=1977');
//SEND REQUEST
xhr.send();

</script>
<table id='box'></table>
</body>
</html>

/* THIS IS THE CODE THAT IS SUPPOSE TO RETRIEVE ALL 250 IMAGES FROM THE COINS VIA THE XMLHttpRequest but i am only getting from 0-99 images only for some reason all the images seem to be there when i inspect the response in the console but cant seem to access all of the images with the 'for in' loop */


r/JavaScriptHelp • • Jan 31 '22

❔ Unanswered ❔ How would i go abouts to disable a button for 12 hours?

1 Upvotes

I want to make an app where you can press a button, and after that it would be disabled and not clickable. It would start an 12 hour timer and after 12 hours the button would be clickable again. But im i dont know how to keep the timer going after the window is closed. Would i need a server of some sort?, or is it possible without?


r/JavaScriptHelp • • Jan 17 '22

❔ Unanswered ❔ What's the difference between return and console.log ?

3 Upvotes

there's more to the problem than this, but for now, why does my for loop stop after 1 iteration when using return? I need the result to be what console.log displays looping through each element.

 const speciesArray = [ 

  {speciesName:'shark', numTeeth:50},    {speciesName:'dog', numTeeth:42},    {speciesName:'alligator', numTeeth:80},   {speciesName:'human', numTeeth:32}];

const sortSpeciesByTeeth = array => {

for (let i = 0; i < array.length; i++){

return array[i].numTeeth    }   } // returns 50

const sortSpeciesByTeeth = array => {

for (let i = 0; i < array.length; i++){

console.log(array[i].numTeeth)    }   } // returns 50, 42, 80, 32


r/JavaScriptHelp • • Feb 14 '22

❔ Unanswered ❔ Need help while saving file

2 Upvotes

I'm trying to implement a functionality where I need to save a file from cloud storage to my local machine. The API expects a local file destination (to save file) as one of the parameters. I want to set this destination based on user prompt.
Is there a way I can do this using React / Javascript where a user can select this location?


r/JavaScriptHelp • • Jan 19 '22

❔ Unanswered ❔ Error while trying to install @discordjs/opus

1 Upvotes

I tried to install my discordbot on my raspberry pi. And it worked. Now we tried to install it on my friends raspberry pi but this error comes up:

npm ERR! code 1 npm ERR! path /home/pi/Desktop/SourceBot/node_modules/@discordjs/opus npm ERR! command failed npm ERR! command sh -c node-pre-gyp install --fallback-to-build npm ERR! Failed to execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/home/pi/Desktop/SourceBot/node_modules/@discordjs/opus/prebuild/node-v93-napi-v3-linux-arm-glibc-2.24/opus.node --module_name=opus --module_path=/home/pi/Desktop/SourceBot/node_modules/@discordjs/opus/prebuild/node-v93-napi-v3-linux-arm-glibc-2.24 --napi_version=8 --node_abi_napi=napi --napi_build_version=3 --node_napi_label=napi-v3' (1) npm ERR! node-pre-gyp info it worked if it ends with ok npm ERR! node-pre-gyp info using [email protected] npm ERR! node-pre-gyp info using [email protected] | linux | arm npm ERR! node-pre-gyp info check checked for "/home/pi/Desktop/SourceBot/node_modules/@discordjs/opus/prebuild/node-v93-napi-v3-linux-arm-glibc-2.24/opus.node" (not found) npm ERR! node-pre-gyp http GET https://github.com/discordjs/opus/releases/download/v0.7.0/opus-v0.7.0-node-v93-napi-v3-linux-arm-glibc-2.24.tar.gz npm ERR! node-pre-gyp ERR! install response status 404 Not Found on https://github.com/discordjs/opus/releases/download/v0.7.0/opus-v0.7.0-node-v93-napi-v3-linux-arm-glibc-2.24.tar.gz npm ERR! node-pre-gyp WARN Pre-built binaries not installable for @discordjs/[email protected] and [email protected] (node-v93 ABI, glibc) (falling back to source compile with node-gyp) npm ERR! node-pre-gyp WARN Hit error response status 404 Not Found on https://github.com/discordjs/opus/releases/download/v0.7.0/opus-v0.7.0-node-v93-napi-v3-linux-arm-glibc-2.24.tar.gz npm ERR! gyp info it worked if it ends with ok npm ERR! gyp info using [email protected] npm ERR! gyp info using [email protected] | linux | arm npm ERR! gyp info ok npm ERR! gyp info it worked if it ends with ok npm ERR! gyp info using [email protected] npm ERR! gyp info using [email protected] | linux | arm npm ERR! gyp ERR! find Python npm ERR! gyp ERR! find Python Python is not set from command line or npm configuration npm ERR! gyp ERR! find Python Python is not set from environment variable PYTHON npm ERR! gyp ERR! find Python checking if "python3" can be used npm ERR! gyp ERR! find Python - executable path is "/usr/bin/python3" npm ERR! gyp ERR! find Python - version is "3.5.3" npm ERR! gyp ERR! find Python - version is 3.5.3 - should be >=3.6.0 npm ERR! gyp ERR! find Python - THIS VERSION OF PYTHON IS NOT SUPPORTED npm ERR! gyp ERR! find Python checking if "python" can be used npm ERR! gyp ERR! find Python - executable path is "/usr/bin/python" npm ERR! gyp ERR! find Python - version is "2.7.13" npm ERR! gyp ERR! find Python - version is 2.7.13 - should be >=3.6.0 npm ERR! gyp ERR! find Python - THIS VERSION OF PYTHON IS NOT SUPPORTED npm ERR! gyp ERR! find Python npm ERR! gyp ERR! find Python ********************************************************** npm ERR! gyp ERR! find Python You need to install the latest version of Python. npm ERR! gyp ERR! find Python Node-gyp should be able to find and use Python. If not, npm ERR! gyp ERR! find Python you can try one of the following options: npm ERR! gyp ERR! find Python - Use the switch --python="/path/to/pythonexecutable" npm ERR! gyp ERR! find Python (accepted by both node-gyp and npm) npm ERR! gyp ERR! find Python - Set the environment variable PYTHON npm ERR! gyp ERR! find Python - Set the npm configuration variable python: npm ERR! gyp ERR! find Python npm config set python "/path/to/pythonexecutable" npm ERR! gyp ERR! find Python For more information consult the documentation at: npm ERR! gyp ERR! find Python https://github.com/nodejs/node-gyp#installation npm ERR! gyp ERR! find Python ********************************************************** npm ERR! gyp ERR! find Python npm ERR! gyp ERR! configure error npm ERR! gyp ERR! stack Error: Could not find any Python installation to use npm ERR! gyp ERR! stack at PythonFinder.fail (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/find-python.js:330:47) npm ERR! gyp ERR! stack at PythonFinder.runChecks (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/find-python.js:159:21) npm ERR! gyp ERR! stack at PythonFinder.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/find-python.js:266:16) npm ERR! gyp ERR! stack at PythonFinder.execFileCallback (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/find-python.js:297:7) npm ERR! gyp ERR! stack at ChildProcess.exithandler (node:child_process:388:7) npm ERR! gyp ERR! stack at ChildProcess.emit (node:events:390:28) npm ERR! gyp ERR! stack at maybeClose (node:internal/child_process:1064:16) npm ERR! gyp ERR! stack at Socket.<anonymous> (node:internal/child_process:450:11) npm ERR! gyp ERR! stack at Socket.emit (node:events:390:28) npm ERR! gyp ERR! stack at Pipe.<anonymous> (node:net:687:12) npm ERR! gyp ERR! System Linux 4.19.42-v7+ npm ERR! gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "configure" "--fallback-to-build" "--module=/home/pi/Desktop/SourceBot/node_modules/@discordjs/opus/prebuild/node-v93-napi-v3-linux-arm-glibc-2.24/opus.node" "--module_name=opus" "--module_path=/home/pi/Desktop/SourceBot/node_modules/@discordjs/opus/prebuild/node-v93-napi-v3-linux-arm-glibc-2.24" "--napi_version=8" "--node_abi_napi=napi" "--napi_build_version=3" "--node_napi_label=napi-v3" npm ERR! gyp ERR! cwd /home/pi/Desktop/SourceBot/node_modules/@discordjs/opus npm ERR! gyp ERR! node -v v16.13.2 npm ERR! gyp ERR! node-gyp -v v8.3.0 npm ERR! gyp ERR! not ok npm ERR! node-pre-gyp ERR! build error npm ERR! node-pre-gyp ERR! stack Error: Failed to execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/home/pi/Desktop/SourceBot/node_modules/@discordjs/opus/prebuild/node-v93-napi-v3-linux-arm-glibc-2.24/opus.node --module_name=opus --module_path=/home/pi/Desktop/SourceBot/node_modules/@discordjs/opus/prebuild/node-v93-napi-v3-linux-arm-glibc-2.24 --napi_version=8 --node_abi_napi=napi --napi_build_version=3 --node_napi_label=napi-v3' (1) npm ERR! node-pre-gyp ERR! stack at ChildProcess.<anonymous> (/home/pi/Desktop/SourceBot/node_modules/@discordjs/node-pre-gyp/lib/util/compile.js:85:20) npm ERR! node-pre-gyp ERR! stack at ChildProcess.emit (node:events:390:28) npm ERR! node-pre-gyp ERR! stack at maybeClose (node:internal/child_process:1064:16) npm ERR! node-pre-gyp ERR! stack at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5) npm ERR! node-pre-gyp ERR! System Linux 4.19.42-v7+ npm ERR! node-pre-gyp ERR! command "/usr/local/bin/node" "/home/pi/Desktop/SourceBot/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build" npm ERR! node-pre-gyp ERR! cwd /home/pi/Desktop/SourceBot/node_modules/@discordjs/opus npm ERR! node-pre-gyp ERR! node -v v16.13.2 npm ERR! node-pre-gyp ERR! node-pre-gyp -v v0.4.2 npm ERR! node-pre-gyp ERR! not ok

npm ERR! A complete log of this run can be found in: npm ERR! /home/pi/.npm/_logs/2022-01-19T22_52_22_476Z-debug.lo


r/JavaScriptHelp • • Jan 24 '22

❔ Unanswered ❔ Auto-Resize an Emoji According To The Website In Use

2 Upvotes

This Emoji translates quite well to various forums across the web (Originally a Discord 22x22 Emoji).

I would like to "teach" my computer to change the image =size? when I "paste" it into site X ,so that the Emoji maintains a size akin to that of the text.

I have no idea how to do this (no programming experience) .When I copy-paste a sentence-Emoji combo from Discord into various forums , the Emoji transforms into an unproportional size compared relatively to the text (in Discord it seems to be rendering at 22x22, but when pasted to forum X it seems to become a 40x40 rendering.

I've had this suggestion: 

const regex = /\[IMG\]https:\/\/cdn\.discordapp\.com\/emojis.*\[\/IMG]/gm; const str = \[IMG=https://cdn.discordapp.com/emojis/935270790675431484.webp?size=44&quality=lossless]; if (regex.test(str)) { //regex to replace the size}`

But, again, no knowledge in programming. Is the aforementioned code Javascript?

Here's the Platinum Trophy image as it appears on the browser version of Discord in the Elements tab (left-click > Inspect) , in DevTools (Chrome):

<IMG aria-label=":PlatinumTrophy:" src="https://cdn.discordapp.com/emojis/935270790675431484.webp?size=44&amp;quality=lossless" alt=":PlatinumTrophy:" draggable="false" class="emoji" data-type="emoji" data-id="935270790675431484">

I see there's a "size=44" section ? Would I be correct in saying that in order to achieve my desired size all I have to do is to somehow teach my computer a function where the "44" goes in and ,say, "20" comes out? If so , how do I go about achieving this? 

I've tried post to r/learnjavascript but I got the " Please fix the above requirements " error when posting, so I thought I'd post here.


r/JavaScriptHelp • • Jan 11 '22

❔ Unanswered ❔ Wellness Check Project Code Issues

2 Upvotes

Hello, I'm trying to set up a script in Google Scripts (uses JS) to send a Covid Wellness Check form to certain groups of people. I barely got a c- in my python coding class and I've never even worked with JS, so I'm shooting my shot on here.

I want to receive an email with the wellness check every day unless it's Martin Luther King Jr. Day (a national holiday on Jan. 17 here in the states). I'm aware the time of day may cause an issue later on, but for now I'm just trying to accomplish what mentioned above.

Why am I not receiving an email when I run this script?

function test() {    var days = [ScriptApp.WeekDay.Monday, ScriptApp.WeekDay.Tuesday, ScriptApp.WeekDay.Wednesday, ScriptApp.WeekDay.Thursday, ScriptApp.WeekDay.Friday];    var current = new Date()    var MLKJDay = new Date(2022,0,17,0,0,0,0)    if (current !== MLKJDay){      ScriptApp.newTrigger("emailMe")}      else {      return;} }           function emailMe() {    MailApp.sendEmail({       to:’[my email address]’,       subject:’Wellness Check Test',       body:'',   }) }