r/JavaScriptHelp • • Sep 04 '21

❔ Unanswered ❔ How do I solve this uncaught DOMException error?

1 Upvotes

I'm currently creating a function where a user can preview an image or video before submit. I did this by making two buttons: one for image files only and the other for video files only. While coding, everything was working fine until I encountered this error in my console:

Uncaught (in promise) DOMException: Failed to load because no supported source was found.

This is my HTML so far:

<div class="image-preview" id="imagePreview">
            <img src="" class="image-preview__image">
          </div>

          <div class="video-preview" id="videoPreview">
            <video controls autoplay muted class="video-preview__video" id="video" src=""></video>
          </div>

        <br>
        <label for="inpFile"><img id="image_icon" src="images/images_icon.png"></label>
        <input id="inpFile" type="file" name="file" style="display:none;" accept="image/*">
        <label for="inpFile2"><img id="video_icon" src="images/videos_icon.png"></label>
        <input id="inpFile2" type="file" name="file" style="display:none;" accept="video/*"> 

This is my JS so far:

//preview image in textarea
	const inpFile = document.getElementById("inpFile");
	const previewContainer = document.getElementById("imagePreview");
	const previewImage = previewContainer.querySelector(".image-preview__image");

	inpFile.addEventListener("change", function() {
		const file = this.files[0];

		if(file){
			const reader = new FileReader();

			previewContainer.style.display = "block";
			previewImage.style.display = "block";

			reader.addEventListener("load", function() {
				previewImage.setAttribute("src", this.result);
			});

			reader.readAsDataURL(file);
		}else{
			previewImage.style.display = null;
			previewImage.setAttribute("src","");
		}
	});

  //preview video in textarea
  const inpFile2 = document.getElementById('inpFile2');
  const video = document.getElementById('video');
  const previewVideoContainer = document.getElementById("videoPreview");
  const previewVideo = previewContainer.querySelector(".video-preview__video");
  const videoSource = document.createElement('source');

  inpFile2.addEventListener('change', function() {
    const file = this.files[0];

    if(file){

      const reader = new FileReader();

      previewVideoContainer.style.display = "block";

      reader.onload = function (e) {
        videoSource.setAttribute('src', e.target.result);
        video.appendChild(videoSource);
        video.load();
        video.play();
      };

      reader.onprogress = function (e) {
        console.log('progress: ', Math.round((e.loaded * 100) / e.total));
      };

      reader.readAsDataURL(file);
    }else{
      previewVideo.style.display = null;
			previewVideo.setAttribute("src","");
    }
  });

Any help would be greatly appreciated thanks : )


r/JavaScriptHelp • • Sep 17 '21

❔ Unanswered ❔ Problem with sessionStorage

2 Upvotes

I currently have a mostly working script that compares two checkbox ID's when the compare button is pressed.

However, after using a sessionStorage script I found online, I found that now my checkbox values don't update unless I refresh the page (since sessionStorage makes it so the browser only sees the last selected value, and not the new one).

Is there any way to KEEP sessionStorage--as in, have the browser remember the last selected checkbox value--but also update the value in the checkboxes WITHOUT refreshing the page?

Much appreciated!

<input data-selector="edit-submit" type="submit" id="edit-submit" value="Search" class="button js-form-submit form-submit btn btn-primary form-control">
<input data-selector="edit-reset" type="submit" id="edit-reset" name="op" value="Reset" class="button js-form-submit form-submit btn btn-primary form-control">
<button type="button" class="btn btn-sm btn-primary" id="compare">Compare</button>
<input type="checkbox" id="td0" class="form-check-input" value="">
<input type="checkbox" id="td1" class="form-check-input" value="">
<input type="checkbox" id="td2" class="form-check-input" value="">
<input type="checkbox" id="td3" class="form-check-input" value="">
<input type="checkbox" id="td4" class="form-check-input" value="">
<input type="checkbox" id="td5" class="form-check-input" value="">
<input type="checkbox" id="td6" class="form-check-input" value="">
<input type="checkbox" id="td7" class="form-check-input" value="">

function onReady() {
    $(function(){
  $("input:checkbox").change(function(){
    var len = $("input:checkbox:checked").length;
    if(len == 0)
      $("#compare[type='button']").prop("disabled", true);
    else
      $("#compare[type='button']").removeAttr("disabled");
  });
});
   $(function(){
    $('input:checkbox').each(function() {
        var $el = $(this);
        $el.prop('checked', sessionStorage[$el.prop('id')] === 'true');
     });

    $('input:checkbox').on('change', function() {
        var $el = $(this);
        sessionStorage[$el.prop('id')] = $el.is(':checked');
   });
});

var all_checkboxes_search = jQuery(':checkbox');
jQuery('#edit-submit').on('click', function(event){
    all_checkboxes_search.prop('checked', false).change();
  });

var all_checkboxes_reset = jQuery(':checkbox');
jQuery('#edit-reset').on('click', function(event){
    all_checkboxes_reset.prop('checked', false).change();
  });

$(function() {
  $("input:checkbox").change(function(index){ 
    var limit = 4;
    if($("input:checkbox:checked").length >= limit) {
      this.checked = false;
  }
});

  var txt = $('input:checked')
  .map(function() { 
  return this.id;
  })
  .get().join(',');
 
$("#compare[type='button']").click(function() { 
    alert(txt);
   });
 });
}
$(document).ready(onReady);

r/JavaScriptHelp • • Sep 21 '21

❔ Unanswered ❔ Why is the data not saving into a live database despite it working in a local server?

2 Upvotes

I am deploying a Website to a live domain via 000webhost.com. My problem is that when I run the application from localhost, It saves the data into the database successfully. But when inserting the data from the live website, it does not insert the data into the SQL server. Also, I did not receive any errors so I'm a bit confused. Here is a link to my Github repo: https://github.com/Rustyrice/rustyrice.github.io.git


r/JavaScriptHelp • • Sep 23 '21

❔ Unanswered ❔ Put links on separate lines

1 Upvotes
//below is the array for the list
const links = [
    {
        label: "Week1 notes",
        url: "WDD330/week1/index.html"
    },
    {
        label: "Week2 notes",
        url: "WDD330/week2/index.html"
    }
];

// grabs the ul

const theList = document.querySelector('#wdd330Assign');


// loops through the links array and grabs the label and sets it in the li
for (i = 0; i <= links.length - 1; i++) {
    const li = document.createElement('li');
    //adding the id addLink so I can loop through and add the a tags inside the li
    li.setAttribute('id', 'addLink');
    li.innerText = links[i].label + ': '

    // const a = document.createElement('a')
    // a.setAttribute('href', links[i].url);

    theList.appendChild(li);
}

//grabs the li nested in the ul 
const theLi = document.querySelector('#addLink');

// loops again to add the links to the li element


for (i = 0; i <= links.length - 1; i++){
    const a = document.createElement('a');
    a.setAttribute('href', links[i].url);
    a.innerText = "Click Here";

    theLi.appendChild(a);
}

The code above is supposed to read from the links list and create an li with info about the link and a link. I have the code working but I want it to display the link beside the information of the link. For example:

Info for link: <link goes here>
Info for second link: <new link goes here>

However, I am running into a situation where it is displaying like this:

Info for link: <link goes here><new link goes here>
Info for second link:

Not really sure how to tackle this without creating another loop that gives a new ID each time for the <li> tags. For instance, #addLink1, #addLink2. If you need me to explain more please let me know.


r/JavaScriptHelp • • Aug 18 '21

💡 Advice 💡 How to create a grid from random generated numbers between min and max values?

2 Upvotes

I'm trying to draw a grid representing random generated integers between (-100-100) (Each cell / square corresponds to an integer). 100 corresponding to the hexadecimal value #FF0000 (red) and -100 corresponding to the hexadecimal value #00FF00 (green), then assigning a color to each cell between the two initial colors according to the value of the integer it represents. An example like "Github contribution grid"


r/JavaScriptHelp • • Sep 04 '21

❔ Unanswered ❔ How do I solve this uncaught DOMException error?

1 Upvotes

I'm currently creating a function where a user can preview an image or video before submit. I did this by making two buttons: one for image files only and the other for video files only. While coding, everything was working fine until I encountered this error in my console:

Uncaught (in promise) DOMException: Failed to load because no supported source was found.

This is my HTML so far:

<div class="image-preview" id="imagePreview">
            <img src="" class="image-preview__image">
          </div>

          <div class="video-preview" id="videoPreview">
            <video controls autoplay muted class="video-preview__video" id="video" src=""></video>
          </div>

        <br>
        <label for="inpFile"><img id="image_icon" src="images/images_icon.png"></label>
        <input id="inpFile" type="file" name="file" style="display:none;" accept="image/*">
        <label for="inpFile2"><img id="video_icon" src="images/videos_icon.png"></label>
        <input id="inpFile2" type="file" name="file" style="display:none;" accept="video/*"> 

This is my JS so far:

//preview image in textarea
	const inpFile = document.getElementById("inpFile");
	const previewContainer = document.getElementById("imagePreview");
	const previewImage = previewContainer.querySelector(".image-preview__image");

	inpFile.addEventListener("change", function() {
		const file = this.files[0];

		if(file){
			const reader = new FileReader();

			previewContainer.style.display = "block";
			previewImage.style.display = "block";

			reader.addEventListener("load", function() {
				previewImage.setAttribute("src", this.result);
			});

			reader.readAsDataURL(file);
		}else{
			previewImage.style.display = null;
			previewImage.setAttribute("src","");
		}
	});

  //preview video in textarea
  const inpFile2 = document.getElementById('inpFile2');
  const video = document.getElementById('video');
  const previewVideoContainer = document.getElementById("videoPreview");
  const previewVideo = previewContainer.querySelector(".video-preview__video");
  const videoSource = document.createElement('source');

  inpFile2.addEventListener('change', function() {
    const file = this.files[0];

    if(file){

      const reader = new FileReader();

      previewVideoContainer.style.display = "block";

      reader.onload = function (e) {
        videoSource.setAttribute('src', e.target.result);
        video.appendChild(videoSource);
        video.load();
        video.play();
      };

      reader.onprogress = function (e) {
        console.log('progress: ', Math.round((e.loaded * 100) / e.total));
      };

      reader.readAsDataURL(file);
    }else{
      previewVideo.style.display = null;
			previewVideo.setAttribute("src","");
    }
  });

Any help would be greatly appreciated thanks : )


r/JavaScriptHelp • • Aug 25 '21

✔️ answered ✔️ How do I split a word to retrieve part of it? Problems with substring?

2 Upvotes

So I come from a pl/sql background, so I think I am making a basic error here..

But I have looped through a series of elements which I know will each contain a class named "ibType-" followed by a type "string"/"id"/"long" etc.

for example,

This is my code

for(var i=0; i < form.elements.length; i++){
                            var e = form.elements[i];
                            var pos = e.className.lastIndexOf("ibType-");
                            console.log ("Starts at "+pos);
                            var classType = e.className.substring(pos);
                            console.log ("ClassType = "+classType);

The problem is that my first console.log is showing the position that the string "starts at", rather than ends at.

start-quote.js:91 Starts at 13
start-quote.js:93 ClassType = ibType-ID
start-quote.js:91 Starts at 0
start-quote.js:93 ClassType = ibType-STRING
start-quote.js:91 Starts at 13
start-quote.js:93 ClassType = ibType-ID
start-quote.js:91 Starts at 13

And the substring doesn't seem to do anything. In this example, I would like the value of classType to be "ID" "STRING" and "ID".

Can anyone point out my problem here?

Thanks in advance


r/JavaScriptHelp • • Sep 03 '21

❔ Unanswered ❔ How do I create a code to detect whether a user has selected an image file or a video file?

1 Upvotes

I want to show a preview of an uploaded video file before submit. I have successfully done this with an image thanks to the following JS, but it is not working with video files...

	const inpFile = document.getElementById("inpFile");
	const previewContainer = document.getElementById("imagePreview");
	const previewImage = previewContainer.querySelector(".image-preview__image");

	inpFile.addEventListener("change", function() {
		const file = this.files[0];

		if(file){
			const reader = new FileReader();

			previewContainer.style.display = "block";
			previewImage.style.display = "block";

			reader.addEventListener("load", function() {
				previewImage.setAttribute("src", this.result);
			});

			reader.readAsDataURL(file);
		}else{
			previewImage.style.display = null;
			previewImage.setAttribute("src","");
		}
	});

So I created another JS function for previewing video files before submit:

  const input = document.getElementById('inpFile2');
  const video = document.getElementById('video');
  const previewContainer = document.getElementById("videoPreview");
  const previewVideo = previewContainer.querySelector(".video-preview__video");
  const videoSource = document.createElement('source');

  input.addEventListener('change', function() {
  const files = this.files || [];

  if (!files.length) return;

  const reader = new FileReader();

  reader.onload = function (e) {
    videoSource.setAttribute('src', e.target.result);
    video.appendChild(videoSource);
    video.load();
    video.play();
  };

  reader.onprogress = function (e) {
    console.log('progress: ', Math.round((e.loaded * 100) / e.total));
  };

  reader.readAsDataURL(files[0]);
});

This is my HTML:

  <div class="image-preview" id="imagePreview">
            <img src="" class="image-preview__image" alt="Video selected">
          </div>

          <div class="video-preview" id="videoPreview">
            <video controls autoplay muted class="video-preview__video" id="video" src=""></video>
          </div>

        <br>
        <label for="inpFile"><img id="image_icon" src="images_icon.png"></label>
        <input id="inpFile" type="file" name="file" style="display:none;">
        <label for="inpFile2"><img id="video_icon" src="images/video_icon.png"></label>
        <input id="inpFile2" type="file" name="file" style="display:none;" accept="video/*">
        <input id="post_button" type="submit" value="Post" style="margin:5px;">

I'm not sure how to create a code that can help detect whether the user has selected an image or video file. An example of this feature is used by Twitter. When you select an image/video to tweet, Twitter would let you preview the image/video in the textarea. That's the feature I want to implement into my website. Any help would be greatly appreciated!


r/JavaScriptHelp • • Aug 25 '21

✔️ answered ✔️ Help with modifying a duration timer display

1 Upvotes

I'm looking for help with tweaking a timer duration which successfully displays upon 'start' and stops successfully upon 'stop'.

However, on the html page , before clicking 'start' this is visible :

And then upon clicking 'start' this displays :

how can I not show : until it all displays?

Also, how can I modify it so that it displays this: 0:00 instead of 00:00 ?

Additionally, how can I delay the timer by 1 second before the timer begins?

Here is the html:

<span id="min"></span>:<span id="sec"></span>

And the js:

var Clock = {
  totalSeconds: 0,
  start: function () {
    if (!this.interval) {
        var self = this;
        function pad(val) { return val > 9 ? val : "0" + val; }
        this.interval = setInterval(function () {
          self.totalSeconds += 1;
          document.getElementById("min").innerHTML = pad(Math.floor(self.totalSeconds / 60 % 60));
          document.getElementById("sec").innerHTML = pad(parseInt(self.totalSeconds % 60));
        }, 1000);
    }
  },
  reset: function () {
    Clock.totalSeconds = null;
    clearInterval(this.interval);
    document.getElementById("min").innerHTML = "00";
    document.getElementById("sec").innerHTML = "00";
    delete this.interval;
  },
  stop: function () {
    clearInterval(this.interval);
    delete this.interval;
  }
};
document.getElementById("start").addEventListener("click", function () { Clock.start(); });
document.getElementById("stop").addEventListener("click", function () { Clock.stop(); });

Any help is appreciated.


r/JavaScriptHelp • • Mar 12 '22

❔ Unanswered ❔ Help with momentjs

2 Upvotes

I've an array abc containing date and time. How can I convert it into time slots of 1 day with limits determined by startDate and endDate with 'x' containing time slots and 'y' containing count of occurrence in those time slots. I have also attached the fiddle below for reference.

http://jsfiddle.net/killMeSak/Lwj2mb7t/9/


r/JavaScriptHelp • • Mar 02 '22

💡 Advice 💡 whenever i open an app i get following error, although javascript and cookies are both enabled on chrome and samsung Internet.

1 Upvotes

Access to this page has been denied because we believe you are using automation tools to browse the website.

This may happen as a result of the following:

Javascript is disabled or blocked by an extension (ad blockers for example) Your browser does not support cookies Please make sure that Javascript and cookies are enabled on your browser and that you are not blocking them from loading.

Reference ID: #dc6ac997-99d8-11ec-8fa2-78796862576b

Report an issue Using an ad-blocker (e.g. uBlock Origin)? Please disable it in order to continue.


r/JavaScriptHelp • • Mar 08 '22

💡 Advice 💡 Any advice?

2 Upvotes

I'm trying to get the user to be able to put there name in the string and replace Demar with it any help would help.

.<!DOCTYPE html>

<html lang="en">

<head>

	<meta charset="utf-8" />

	<title></title>

</head>

<body>	

	<script>

		Var myString = "Kevin, Kobe, Kyrie, Lamelo, Demar";

		mar myRegEXP = /Demar/;

		

		myString = myString.replace (myRegExp, "GiGi");

		alert(myString);

	</script>

	</body>

r/JavaScriptHelp • • Mar 23 '22

❔ Unanswered ❔ noVNC and require.js

2 Upvotes

I have an existing project using require.js which uses an older version of noVNC. I need to upgrade the noVNC so I can use user/password authentication, but I'm having no luck getting the noVNC to compile to an AMD version.

I've run across various instructions, but they usually follow this pattern:

git clone https://github.com/novnc/noVNC/
cd noVNC
npm update
node ./utils/use_require.js --as amd --clean

With the 1.3 version of noVNC, the use_require.js script does not take an "--as" parameter, and the compiled version it spits out doesn't appear to be a require.js version - it doesn't start with a define. Trying to use it results in this error:

Uncaught ReferenceError: exports is not defined
    <anonymous> http://127.0.0.1:8080/testapp/lib/novnc/rfb.js?v=1648066918354:5

I tried adding "var exports={}" to the top of the page, but that screws up all kinds of things - presumably some other components are trying to detect commonjs vs AMD and get confused.

In the master version from github the use_require.js file is renamed to convert.js but has the same problem. Trying to compile the 1.2 version yields this cryptic error:

/home/dwargo/noVNC-1.2.0/utils/use_require.js:130
        throw new Error("you must specify an import format to generate compiled noVNC libraries");
        ^

Error: you must specify an import format to generate compiled noVNC libraries
    at makeLibFiles (/home/dwargo/noVNC-1.2.0/utils/use_require.js:130:15) 
    at Object.<anonymous> (/home/dwargo/noVNC-1.2.0/utils/use_require.js:322:1)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
    at internal/main/run_main_module.js:17:47

Looking at the source of use_require.js it seems like --as specifies the input format, so I have no clue what to do about that.

I'm on my second day of throwing this thing at a wall with no luck - I'm hoping someone has walked this road before. I guess I can hand-paste the define blocks from the old version, but that seems painful.


r/JavaScriptHelp • • Mar 02 '22

❔ Unanswered ❔ Hello! I am new here and I was wondering if someone could help me with some javascript on the platform tradovate (I am not a coder)

1 Upvotes

Hello I am needing help with setting up an indicator on tradovate that will show me the min and max of delta. I have screenshots of what I want and on the platform they already have something close to what I want but it is missing certain things

I would post the pictures of what I want but it will not let me here


r/JavaScriptHelp • • Mar 14 '22

❔ Unanswered ❔ Get count and format

2 Upvotes

I have an object dateRange ={ 2021-08-06 - 2021-09-06 : 0, 2021-09-06 -2021-10-06 : 0}

I also have another array dateArr=[2021-08-06, 2021-11-06]. Desired res = [{key: 2021-08-06 - 2021-09-06 , value: 1}, { key: 2021-09-06 -2021-10-06 , value: 0}] where value contains the number of occurrences of values inside dateArr as per dateRange.

How can I achieve this?


r/JavaScriptHelp • • Feb 23 '22

❔ Unanswered ❔ It says that the html isnt declared(using notepad++)

1 Upvotes

<html> <head> <title>4 of my favourite places</title> </head> <body>

Hey, I'm Kelsi and I like visiting new places. <br><br> Here are my 4 favourite places.

this picture of snow valley where I go skiing during the winter.<br> <img src="SnowValley" width="300" height="250"> <br>

I usually go ski there with my family. The place has multiple places where one can go ski each varying in difficulty.<br>

This is a picture of where Downtown Toronto<br> <img src="DownTown"> <br>

I love Downtown Toronto as everything there feels big and I like the energy over there.<br>

My 3rd favourite place is Sunway Lagoon.<br> <img src="SunwayLagoon"> <br>

Sunway Lagoon is found in Malaysia. It is found in Malayasia and is owned by a hote company with its own mall next to it along with the hotel.<br>

My last favourite place is Canada Wonderland.<br> <img src="Wonderland"> <br>

Winter Wonderland is a giant amusement park with a lot of roller coasters.<br>

</body></html>


r/JavaScriptHelp • • Mar 06 '22

💡 Advice 💡 need help with google javascript map

2 Upvotes

hi!
I'm building a project which shows the live location of active users on an app but I'm not able to update the position of the marker on the map due to which when the website receives a new location it just add a new marker instead of updating the last marker.

can anyone help me with this?

#javascript #

<script>
        let map;
        let params3;

        params3 = JSON.parse(localStorage.getItem('test6'));
        





        function initMap() {
            //Map options
            var options = {
                zoom: 12,
                center: { lat: 30.695, lng: 80.124 }
            }
            // new map
            map = new google.maps.Map(document.getElementById('map'), options);
            // customer marker
            var iconBase = './icon6.png';

            //array of Marrkeers
            // var markers = [
            //     {
            //         coords: { lat: 28.6934080, lng: 77.1242910 }, img: iconBase, con: '<h3> This Is your Content <h3>'
            //     },
            // ];



            //loopthrough markers
            
            if (params3) {
                console.log(params3);

                for (var i = 0; i < params3.length; i++) {
                    //add markeers
                    addMarker(params3[i]);
                    // console.log(params3[i]);
                }

            }


            //function for the plotting markers on the map
            function addMarker(props) {

                if (props.status == 'ONLINE') {
                    var marker = new google.maps.Marker({
                        position: props.coords,
                        map: map,
                        // icon: props.img
                    });
                    var infoWindow = new google.maps.InfoWindow({
                        content: props.con,
                    });
                    marker.addListener("click", () => {
                        infoWindow.open(map, marker);
                    });

                }

            }
}
</script>

r/JavaScriptHelp • • Dec 20 '21

✔️ answered ✔️ What shows in the console? I got 6. The question says it's 4. HELP ME!!! (Kevin Hart voice)

3 Upvotes

var sum = 0;

for (var = i; i<=3; i++) {

if (i==2) {

continue;

}

sum += i;

}

console.log(sum);


r/JavaScriptHelp • • Nov 18 '21

💡 Advice 💡 Snippet Problem Not Loading Correctly In Browser (Jekyll)

2 Upvotes

So I'm really not a JS guy in the slightest, but wanted to basically render a CSV as table on my Jekyll site - I have this working with the following script.

Only problem is it never seems to load the table first time, I need to click refresh in the browser for it to appear - does anyone have any ideas as to what could be the cause of this?

Cheers!

<script>
	window.onload = function() {
		with(new XMLHttpRequest()) {
			onreadystatechange = cb;
			open('GET', 'https://raw.githubusercontent.com/clintjb/A350-Tracking/main/flight_data_a350.csv', true);
			responseType = 'text';
			send();
		}
	}

function cb() {
	if (this.readyState === 4) document.getElementById('A350')
		.innerHTML = tbl(this.responseText);
}

function tbl(csv) {
	return csv.split('\n')
		.map(function(tr, i) {
			return '<tr><td>' +
				tr.replace(/,/g,'</td><td>') +
				'</td></tr>';
		})
		.join('\n');
}
</script>
<table border="0" style='font-size:50%' id="A350"></table>

r/JavaScriptHelp • • Dec 06 '21

❔ Unanswered ❔ JS/Jquery Radio Button & Text Box Selection

1 Upvotes

I'm very new to JS and am working on a site with code I didn't write, but am trying to correct. Here's how to get to what I'm looking at:

  1. Go to FS Shop

  2. Add anything to your cart and go to to the Checkout Page.

  3. Scroll to the bottom and click the Continue button.

  4. A donation modal will pop up.

    • When you click the text box for the "Enter Amount" option, the radio button is not filled.

    • If you click that radio button, the curser does not move to the text box.

    • If you select one of the other amounts like $50 and then click the text box to enter $5, the radio button for $50 stays filled.

    • You can see that when you click the text box, the associated radio button blinks quickly so something is happening, but not the correct thing.

The 3 main files for this are:

  • checkout.js

  • donation.js

  • jquery-donation.js

When I copy the code from jquery-donation.js to the browser console, it works correctly. However, it doesn't work with the file simply added to the bottom of the page. jquery-donation.js is found, but not working.

There seems to be a conflict or something between this file and checkout.js.

Is anyone able to provide some guidance? I'd be super appreciative to learn how to fix this. TYIA!

Edit: Clarified description


r/JavaScriptHelp • • Dec 31 '21

✔️ answered ✔️ Why is my "for" loop not working properly?

2 Upvotes

I am trying to create a button element for each corresponding letter in currentQuestion for the quiz I am making. However, when I run the loop. It creates a button element for ALL answers to every question in the quiz. Does anyone know why? Thank you!

var quizQuestionsContainer = document.getElementById("quiz");
var quizQuestion = document.getElementById("quiz-question");
var buttonsContainer = document.getElementById("buttons-container");
var startButton = document.getElementById("start");

startButton.addEventListener("click", function() {
  buttonsContainer.removeChild(startButton);
  quizQuestions.removeChild
  displayQuestion();
});

var displayQuestion = function() {
  quizQuestions.forEach ((currentQuestion) => {
    currentQuestion.answers
      for (letter in currentQuestion.answers) {
      var optionButton = document.createElement("button")
      optionButton.id = "option-button"
      optionButton.textContent = currentQuestion.answers[letter];
      buttonsContainer.appendChild(optionButton);
    }
    quizQuestion.innerText = currentQuestion.question
  });
};


// quiz questions 
var quizQuestions = [
    {
      question: "Inside the HTML document, where do you place your JavaScript code?",
      answers: {
        a: "Inside the <script> element",
        b: "Inside the <link> element",
        c: "Inside the <head> element",
        d: "In the <footer> element"
      },
      correctAnswer: "a",
      feedback: "Nice job! You place your JavaScript inside the <script> element of the HTML Document is correct."
    },
    {
      question: "What operator is used to assign a value to a declared variable?",
      answers: {
        a: "Double-equal (==)",
        b: "Colon (:)",
        c: "Equal sign (=)",
        d: "Question mark (?)"
      },
      correctAnswer: "c",
      feedback: "Awesome! The correct way to assign a variable is with an equal sign(=)."
    },
    {
      question: "What are the six primitive data types in JavaScript?",
      answers: {
        a: "sentence, float, data, bigInt, symbol, undefined",
        b: "string, number, boolean, bigInt, symbol, undefined",
        c: "sentence, int, truthy, bigInt, symbol, undefined",
        d: "string, num, falsy, bigInt, symbol, undefined"
      },
      correctAnswer: "b",
      feedback: "Stellar! JavaScript has a total of six primitive data types: string, number, boolean, bigInt, symbol, undefined."
    },
    {
        question: "What is the difference between && and ||?",
        answers: {
          a: "The logical operator && returns true if both expressions are true while the logical operator || returns true if one expression or the other returns true.",
          b: "The logical operator && returns true if one expression is true while the logical operator || returns true if both expressions returntrue true.",
          c: "The logical operator && returns true if none of the expressions are true while the logical operator || returns true if one expression or the other returns true.",
          d: "The logical operator && returns true if both expressions are true while the logical operator || returns false if one expression or the other returns true."
        },
        correctAnswer: "a",
        feedback: "High-five! The logical operator && returns true if both expressions are true while the logical operator || returns true if one expression or the other returns true. Check out some of the other operators available to you in the MDN Web Docs."
      },
      {
        question: "How do we declare a conditional statement in JavaScript?",
        answers: {
          a: "difference...between",
          b: "for loop",
          c: "while loop",
          d: "if...else"
        },
        correctAnswer: "d",
        feedback: "Amazing! if... else is most definitely how we declare a conditional statement. This is something you will use every day as a JavaScript developer."
      },
      {
        question: "How do we stop a loop from from repeating indefinitely?",
        answers: {
          a: "A loop will stop executing when the condition is true.",
          b: "We have to explicitly end the loop with the break keyword.",
          c: "A loop will stop executing when the condition is false.",
          d: "When we have iterated through half of the condition."
        },
        correctAnswer: "c",
        feedback: "Fantastic! In JavaScript a loop will stop executing when the condition is false. Have a look at the documentation to solidify your knowledge of loops."
      },
      {
        question: "Which statement below is not true about functions in JavaScript?",
        answers: {
          a: "Functions can be reused throughout your code",
          b: "A function must always be assigned an identifier",
          c: "Functions can receive arguments that can alter the output of a function",
          d: "Functions are able to be recursive."
        },
        correctAnswer: "b",
        feedback: "You're doing great! Functions without identifiers are called anonymous functions which are used quite frequently used in JavaScript. Make sure you are familiar with functions and how they work."
      },
      {
        question: "What are the two types of scope JavaScript uses?",
        answers: {
          a: "Outside and Inside",
          b: "Surrounding and Inner",
          c: "Abroad and Local",
          d: "Global and Local"
        },
        correctAnswer: "d",
        feedback: "Nice job! JavaScript has two forms of scope, global and local. Have a look at the documentation on scope because it is something that will continuously during your JavaScript journey."
      },
      {
        question: "As a developer, I want to be able to remove the last element of my array and I want to also be able to add a new element to the beginning of my array. Which two array methods should I use?",
        answers: {
          a: "concat() and shift()",
          b: "forEach() and pop()",
          c: "pop() and unshift()",
          d: "push() and sort()"
        },
        correctAnswer: "c",
        feedback: "Awesome! The pop array method removes the last element of an array and the unshift method adds an element to beginning of the array."
      },
      {
        question: "How do we access a value stored in an object?",
        answers: {
          a: "Period notation, Square bracket notation",
          b: "Dot notation, Bracket notation",
          c: "Dot notation, Curl bracket notation",
          d: "Equal notation, Abstract notation"
        },
        correctAnswer: "b",
        feedback: "Stellar job! We have two ways of accessing data inside of an object, dot notation and bracket notation. Have a look at the documentation to better understand the behavior of objects."
      }
  ];

<!-- HTML --> 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Fundamentals Quiz</title>
    <link rel="stylesheet" href="./assets/css/style.css">
</head>
<body>
    <h1>JavaScript Fundamentals Quiz</h1>

<!-- display questions -->
<div class="quiz-container">
  <div id="quiz">
    <p id="quiz-question">Quiz Question Text Here</p>
  </div>
</div>

<!-- buttons -->
<div id="buttons-container" class="buttons-container">
    <button id="start">Start Quiz</button>
</div>

<!-- display results -->
<div id="results"></div>

<script src="./assets/js/script.js"></script>
</body>
</html>

r/JavaScriptHelp • • Dec 09 '21

💡 Advice 💡 Assistance

2 Upvotes

Reposting as that I put it in the wrong subreddit.!

I am a complete noob when it comes to JavaScript. Honestly, this is one of the most difficult languages I've been trying to grasp. In the last couple of weeks I've been taking my course. I signed up thinking that it'd be a little similar coming to the web development I took prior. But I was sadly mistaken...

I honestly feel like a dumbass, I've been trying to build an API for my final assignment. And honestly I just don't get the material. It's there but just to remember what to call, and how to execute it. It's just mind-boggling to me. If anyone's available to possibly , Go over some things with me. And give me a few pointers I'd really appreciate it. :(


r/JavaScriptHelp • • Jan 05 '22

💡 Advice 💡 hi guys i need your help with this code how to make that "lives--" work properly? p.s I am writing Breakout Game code

1 Upvotes

// you lose 1 live each time fall at bottom

if(ball.getY() + ball.getRadius() > getHeight()){

pause();

ball.setPosition(getWidth()/2, getHeight()/2);

lives--;

if(lives == 0){

stopTimer(draw);

var txt = new Text("Game Over", "30pt Arial");

txt.setPosition(getWidth()/2 - 100, getHeight()/2);

txt.setColor(Color.red);

add(txt);

}

}

r/JavaScriptHelp • • Dec 20 '21

❔ Unanswered ❔ Help with Jquery click

1 Upvotes

Everything works except the jquery click on the button. The below message comes up?

"Uncaught ReferenceError: JQuery is not defined at eval"

jQuery('#order_refund').click(function () {
    jQuery('#sales_order_view_tabs_order_invoices').click()
    var checkExist = setInterval(function() {
    if (jQuery('a[href*="/sales/order_invoice/view/invoice_id/"]')[0]){
        console.log('Found!');
        clearInterval(checkExist);
        JQuery('a[href*="/sales/order_invoice/view/invoice_id/"]').click();
    } else {
    console.log('Not Found!');
    }
}, 200); // check every 100ms
});

Background

I'm using tamper monkey to check if a link exists, as soon as it appears (Loaded via ajax) it should be clicked automatically.

The code above clicks into the correct section then waits for the loading of the link, console shows the "not found" & "found" which then should click on the link.


r/JavaScriptHelp • • Jan 07 '22

❔ Unanswered ❔ Image directory query and display

2 Upvotes

Hey guys,

I am completely lost on this one so I will try my best to explain my situation and what I am trying to achieve.

If you look at a website like Channelate.com you can see that they use a database called comicctrl to present their content.

I can't really justify using a database per content page and so I just wanted to achieve the following:

- Link an image directory on my server to display its contents in a container on the webpage.
- Only display the newest image within the directory within the container.
- Add a 'forward' and 'backward' button that goes to the next newest or next oldest image in the directory and displays that instead.
- Add a 'random' button that randomly selects the image in the directory to display in the container.

On the face of it this seems like it should be completely achievable but I am struggling to find anything online that applies to this situation as I understand its a relatively specific use case.

thank you in advance!

Josh