Hide/show div by a radio button from another div

I want to make a survey where you need to click radio buttons with value yes or no from a div and another div with another radio button will come out. These will continue until the 4th div came out.

The problem I’m encountering here is, when I re-click the 1st div button, the 3rd and 4th div won’t hide. And when i re-click the 2nd div button, the 4th div won’t hide too. Below is my code.

<form class="px-4" method="post">
   <div class="form-check mb-2">
      <input class="form-check-input" type="radio" name="response" value="yes" required onclick="showSolution('yes')">
      <label class="form-check-label" for="radio2Example1">Yes</label>
      <input class="form-check-input" type="radio" name="response" value="no" required onclick="showSolution('no')">
      <label class="form-check-label" for="radio2Example2">No</label>
   </div>
</form>

<!-- Recommendation Solution Section -->
<div id="solution" style="display: none;">
   <hr>
   <p style="text-align: left;" id="solutionText">
   <!-- Recommendation Solution will be displayed here -->
   </p>
   <div style="text-align: center;" id="additionalSolutionRadio">
   <!-- Additional Recommendation Solution Radio Buttons will be displayed here -->
   </div>
</div>

<!-- Additional Recommendation Solution Section -->
<div id="additionalSolution" style="display: none;">
   <hr>
   <p style="text-align: left;" id="additionalSolutionText">
   <!-- Additional Recommendation Solution will be displayed here -->
   </p>
   <div style="text-align: center;">
      <input type="radio" name="additional_solution" value="yes" required onclick="showAdditionalSolution2('yes')"> Yes 
      <input type="radio" name="additional_solution" value="no" required onclick="showAdditionalSolution2('no')"> No
   </div>
</div>

<!-- Additional Recommendation Solution 2 Section -->
<div id="additionalSolution2" style="display: none;">
   <hr>
   <p style="text-align: left;" id="additionalSolutionText2">
   <!-- Additional Recommendation Solution 2 will be displayed here -->
   </p>
</div>

<div class="w3-white w3-container w3-padding-32" style="margin-top:30px;padding-right:34px"><p class="w3-right"></a></p></div>

<script>
// Display solution based on user's response
function showSolution(response) {
  var solutionText = document.getElementById("solutionText");
  var solutionDiv = document.getElementById("solution");
  var additionalSolutionRadio = document.getElementById("additionalSolutionRadio");

  if (response === 'yes') {
    solutionText.innerHTML = "Problem Identified: Operating System Errors<br><br>" +
                            "Recommendation solution:<br><br>" +
                            "Have you used the system restore points to revert to a previously stable state? For macOS, have you used Disk Utility to repair disk errors?<br>";

    // Show the radio buttons for additional solution
    additionalSolutionRadio.innerHTML = '<input type="radio" name="additional_solution" value="yes" required onclick="showAdditionalSolution('yes')"> Yes ' +
                                        '<input type="radio" name="additional_solution" value="no" required onclick="showAdditionalSolution('no')"> No';

  } else {
    solutionText.innerHTML = "No problem identified. Your device is working fine.";
    // Hide the radio buttons for additional solution
    additionalSolutionRadio.innerHTML = '';
  }
  // Show the solution section
  solutionDiv.style.display = "block";
}

// Display additional solution based on user's selection
function showAdditionalSolution(additionalSolution) {
  var additionalSolutionText = document.getElementById("additionalSolutionText");
  var additionalSolutionDiv = document.getElementById("additionalSolution");

  if (additionalSolution === 'yes') {
    additionalSolutionText.innerHTML = "Additional Recommendation: <br><br>" +
                                      "Have you back up your data and consider reinstalling or refreshing the operating system?";
  } else {
    additionalSolutionText.innerHTML = "Try the system restore points to revert to a previously stable state. For macOS, used Disk Utility to repair disk errors.";
  }

  // Show the additional solution section
  additionalSolutionDiv.style.display = "block";
}

// Display additional solution 2 based on user's selection
function showAdditionalSolution2(additionalSolution2) {
  var additionalSolutionText2 = document.getElementById("additionalSolutionText2");
  var additionalSolutionDiv2 = document.getElementById("additionalSolution2");

  if (additionalSolution2 === 'yes') {
    additionalSolutionText2.innerHTML = "Additional Recommendation 2: <br><br>" +
                                      "Try to contact the technician if you still cannot solve the problem using the recommended solution.";
  } else {
    additionalSolutionText2.innerHTML = "Try to back up your data and consider reinstalling or refreshing the operating system.";
  }

  // Show the additional solution 2 section
  additionalSolutionDiv2.style.display = "block";
}
</script>

I think I need to add the name attribute for both Additional Solution but I’m not quite sure how to add it.

I would appreciate it if someone can fix my mistakes. Thank you.

javascript random number multiple times with one getElementById

I want to use a random number result in a span id multiple times
But even cloning or delegating the result only appears once in the result and others appear blank

I don’t know how to do it could help me?

javascript

var min = 50;
var max = 150;
var play1;
var play2;


window.onload = function() {
  play1 = Math.floor(Math.random() * (max - min + 1)) + min;
  max = 10 - play1
  document.getElementById("yourNumber").innerHTML = play1;

  if (play1 < 10 ) {
    play2 = Math.floor(Math.random()*(max-min+1)) + min; 
  } else {
    play2 = Math.floor(Math.random() * 10) + 1;
  }
  document.getElementById("yourNumber1").innerHTML = play2;

}

HTML

 (<span id="yourNumber"></span> user log)

 (<span id="yourNumber1"></span> users logs)
 (<span id="yourNumber1"></span> users logs)
 (<span id="yourNumber1"></span> users logs)
 (<span id="yourNumber1"></span> users logs)

thank you!

Try to clone and delegate the random number

Need display the other four results with a different number

Clickable areas in SVG image that will lead to another image src

Trying to create a point and click adventure game with SVG images and clickable path areas. For example, if you’re in a hall way, and you click on a door, the img src will change to the next room corresponding with that door. I’m able to use addEventListener “click” and alert when the specific area is clicked. I just can’t seem to get an idea on how to change the img src to the next room corresponding with that clicked area.

 //example img
<svg>
 <image xlink:href="/pointAndClickImg/Main Hall.svg"/>
 <path id="mainhall-left-door"/>
 <path id="mainhall-right-door/>
</svg>
 //example js that works with clicking and alerting
let mainHallLeftDoor = document.getElementById("leftdoor")
let mainHallRightDoor = document.getElementById("rightdoor")


mainHallLeftDoor.addEventListener("click", function() {
    alert("left door clicked")
    
})

mainHallRightDoor.addEventListener("click", function() {
    alert("right door clicked")
})

D3.js Line Chart Without Weekends

I am brand new to D3.js and am working on a school project. The task is for me to produce a line chart based on data with the following format:

[
{"date":"2023-12-01", "value":99.6},
{"date":"2023-12-04", "value":99.3},
{"date":"2023-12-05", "value":99.2},
{"date":"2023-12-06", "value":99.14},
...
]

Each data point consists of a single date and single value.
There are no dates present in the dataset that correspond to weekends because it is financial data.

The first thing I tried was doing a scaleTime(), but that resulted in weekends appearing on my X-axis.

The next thing I tried was a scaleBand() like so:

const x = d3.scaleBand().domain(data.map(d => d.date)).range([0, width])

const line = d3.line()
    .x(d => x(d[0]) as number)
    .y(d => y(d[1]))

However, this produced a weird result for me with vertical lines. No weekends showed on the X-axis but the actual line looked crazy!

I am desperate to figure this out. A newbie would appreciate any advice anyone has!

Mobx computed not updating

mobx getter does not seem to react to changes in localStorage.

class Test {
  constructor() {
    makeAutoObservable(this);

    this.setCount = this.setCount.bind(this);
  }

  private static _instance: Test;
  static get instance(): Test {
    if (!this._instance) {
      this._instance = new Test();
    }
    return this._instance;
  }

  get count(): number | null {
    const value: string | null = localStorage.getItem("count");
    if (!value) {
      return null;
    }
    return JSON.parse(value);
  }

  // was 0, updating to 1
  setCount(newValue: number): void {
    localStorage.setItem("count", JSON.stringify(value));
    console.log(
      "updated count",
      newValue, // 1
      "getter local storage?",
      this.count, // 0, old value !!!!
      "direct access local storage?",
      JSON.parse(localStorage.getItem("count") ?? "null"), // 1, new value
    );
  }
}

direct access local storage after the update logs the new value, but getter local storage, which runs the same code behind a mobx computed, does not update unless a hard refresh occurs.

I have all functions in this class observable in the constructor, and the class is initialized once at the app root (logged initialization to be sure). All references use Test.instance, so it’s not reinitializing the class.

Local storage is not async in any way, so it shouldn’t lag in its update.
I’m perplexed.

I know I can just set the value as an observable and not use a computed getter to resolve this, but I’d like to know the fundamental reason behind this.

how to call a method of a javascript class from another method of the same class [closed]

I’m studing nodejs and ES6 and i tryed to run this code from a module i have writed:

class myDate
{
    myDateTime()
    {
        return Date();
    }
    myDateTimeAction(req, res){
        res.writeHead(200, {'content-Type': 'text/html'});
        res.write(`The date and time are currently: ${this.myDateTime()}`);
        res.end();
    }
}
exports.myDateTimeClass = myDate;

but when i run this code, nodejs prompt: TypeError: this.myDateTime is not a function

What i have to do to make this code run correctly?

Trying to make a countdown on a filter in Lens Studio, countdown stuck

Im trying to make a countdown in lens studio that ends on a speficic time, but when i try to edit the timer it only goes from 58:45 and 57:00 minutes. How do i fix it, here is the script.

Iv`e tried many things but it wont work. I tried to correct the startTimer function to properly calculate the time remaining until the target timestamp.

Iv`e also tried to make sure to use the correct variable for the countdown duration.

This is the timer.js:

// ---- Start Timer Object Script ----

//@input Asset.Texture[] timerTextures
//@input Component.SpriteVisual[] columns

var maxTime = 0;
var timerType = 'countdown';
var time = 0;
var minutes = 0;
var seconds = 0;
var minutesTens = 0;
var minutesOnes = 0;
var secondsTens = 0;
var secondsOnes = 0;

global.timerSeconds = 0;
global.timerActive = false;

global.startTimer = function(targetTimestamp, type) {
if (!global.timerActive) {
    if (type === 'stopwatch' || type === 'countdown') {
        timerType = type;
        print(timerType + ' is starting');
        global.timerActive = true;

        // Calculate the initial time difference
        const currentDate = new Date().getTime();
        const initialTimeDifference = targetTimestamp - currentDate;
        
        // For countdown, set the countdown duration in seconds
        time = type === 'countdown' ? Math.max(initialTimeDifference / 1000, 0) : 0;  // Ensure time is non-negative
        global.timerSeconds = time;

        updateTime.reset(0);
    } else {
        print('type invalid');
    }
} else {
    print('timer already started');
}
}

 global.stopTimer = function(callback) {
if (global.timerActive) {
    global.timerActive = false;
    print(timerType + ' finished');
    if (callback) {
        callback(arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]);
    }
} else {
    print('No stopwatch/countdown initialized');
}
}

var updateTime = script.createEvent("DelayedCallbackEvent");
updateTime.bind(function(eventData, callback, cb) {
minutes = Math.floor(time / 60)
seconds = time - (minutes * 60)

if (minutes > 9) {
    minutesTens = Number(String(minutes).charAt(0));
    minutesOnes = Number(String(minutes).charAt(1));
} else {
    minutesTens = 0;
    minutesOnes = Number(String(minutes).charAt(0));
}
if (seconds > 9) {
    secondsTens = Number(String(seconds).charAt(0));
    secondsOnes = Number(String(seconds).charAt(1));
} else {
    secondsTens = 0;
    secondsOnes = Number(String(seconds).charAt(0));
}

updateTimerSprites();

// start change time
if (global.timerActive) {
    if (timerType === 'countdown') {
        time--;
        global.timerSeconds--;
        if (time >= 0) {
            updateTime.reset(1);
        } else {
            global.stopTimer();
        }
    } else {
        time++;
        global.timerSeconds++;
        if (time <= maxTime) {
            updateTime.reset(1);
        } else {
            global.stopTimer();
        }
    }
}
});

function updateTimerSprites() {
script.columns[0].mainPass.baseTex = script.timerTextures[secondsOnes];
script.columns[1].mainPass.baseTex = script.timerTextures[secondsTens];
script.columns[2].mainPass.baseTex = script.timerTextures[minutesOnes];
script.columns[3].mainPass.baseTex = script.timerTextures[minutesTens];
}

And this is Script.js:

const targetTimestamp = new Date("2024-01-01T00:00:00Z").getTime();
global.startTimer(targetTimestamp, 'countdown');

Jcrop have selected area follow scroll

I am creating a website where one functionality is that users can select an area of an image from which to extract text from.

I have put my image in a scrollable div to save space.

<div id="image-container" style="width: 100%; height:75%; overflow:scroll; overflow-x:hidden;">
    <img src="data:image/png;base64,{{ image }}" style="object-fit: cover; width: 100%; height: auto;" id="target" >
</div>

When I am selecting the area the program looks like this image. And when i try to scroll the crosshair moves but the selected area does not want to follow it image.

My Jcrop code:

var jcropApi
var scroll = 0

$(document).ready(function(){
    $('#target').Jcrop({
        onSelect: showCoords,
        onChange: showCoords
    })
})

function showCoords(c) {
    $('#image-container').on('scroll', function(){
        scroll = $('#image-container').scrollTop()
    })

    c.y2 += scroll

    jcropApi = this
}

function getSelectedImageData() {
    if (jcropApi) {
        var canvas = document.createElement('canvas')
        var context = canvas.getContext('2d')

        // Get the selected coordinates
        var selection = jcropApi.tellSelect()

        // Set the canvas size to the selection size
        canvas.width = selection.w
        canvas.height = selection.h

        // Draw the cropped region to the canvas
        context.drawImage(jcropApi.ui.holder.find('img')[0], selection.x, selection.y, selection.w, selection.h, 0, 0, selection.w, selection.h)


        // Get the data URL from the canvas
        var dataUrl = canvas.toDataURL('image/png')
        
        input = document.getElementById('image')
        image = document.getElementById('target')
        x1 = document.getElementById('x1')
        y1 = document.getElementById('y1')
        x2 = document.getElementById('x2')
        y2 = document.getElementById('y2')

        input.value = dataUrl
        x1.value = selection.x 
        y1.value = selection.y 
        x2.value = (selection.w + selection.x) 
        y2.value = (selection.h + selection.y) 
            
    } else {
        console.log('Jcrop instance not initialized.')
    }
}

How can I make the selected area follow the cursor ?

Blazor function for drag and drop

Trying to make a function in .razor file to be able to drag, drop and show the name of the .pdf, .png and .jpg files in the console. This is the element in HTML

<div class="bg-white flex flex-col items-center justify-center py-20 border border-slate-200 rounded-md relative" id="fileDropArea">
                    <img src="assetsAIDocReadericonsfile-upload-input.svg" alt="Icon for upload file" class="w-8">
                    <p>Drag & drop or <span class="text-tertiary">browse</span> your files</p>
                    <input type="file" accept=".pdf, .png, .jpg" class="absolute top-0 left-0 h-full w-full cursor-pointer opacity-0" id="fileInput"/>
                    <p id="fileName"></p>
                </div>

but I really don’t imagine how to do the function or which event to envoke because I’m just starting with blazor.

I tried to do a JavaScript function and insert it in the .razor file but didn’t quite work. I called it on the @onchange event of the input, but got several errors. This is the function

const fileInput = document.getElementById('fileInput');
const filenameContainer = document.getElementById('fileName');
const dropzone = document.getElementById('fileDropArea');

fileInput.addEventListener('change', function() {
    filenameContainer.innerText = fileInput.value.split('\').pop();
    console.log(fileInput.value);
});

['dragenter', 'dragover'].forEach(eventName => {
    dropzone.addEventListener(eventName, function() {
        dropzone.classList.add('bg-background');
    });
});

['dragleave', 'drop'].forEach(eventName => {
    dropzone.addEventListener(eventName, function() {
        dropzone.classList.remove('bg-background');
    });
});

// Prevent default behavior for drag events on the file input
fileInput.addEventListener('dragover', function(event) {
    event.preventDefault();
});

fileInput.addEventListener('drop', function(event) {
    event.preventDefault();
});

Are there any issues using reacts useSyncExternalStore with Nextjs and the App router?

I was wondering if there are any issues using the useSyncExternalStore hook with Nextjs 13+ and the app directory? I know redux suggests you do no global stores Redux with nextjs due the the way nextjs handles requests. i was curious if the same would be true for the useSyncExternalStore hook doing something like the following:

import { useSyncExternalStore } from 'react'

function createStore(initialStore) {
  let store = initialStore
  const listeners = new Set()

  function setStore(newStore) {
    store = newStore
    listeners.forEach(listener => listener(store))
  }

  function subscribe(listener) {
    listeners.add(listener)
    return () => listeners.delete(listener)
  }

  function getStore() {
    return store
  }

  function useStore() {
    return useSyncExternalStore(subscribe, getStore)
  }

  return [useStore, setStore, getStore]
}

export const [useStore, setStore, getStore] = createStore({ count: 0 })

Are there some gotchas here that I should be aware of because this is technically a global store as well? Any input here would be appreciated before I go and use something that could possibly not work.

Vue Computed Method is not rendering in HTML

Hi so I have been stuck with a problem and have spent hours upon hours trying to solve it with no success. I have an array of indices (specificIndices) that is being read by an object (filteredWordsForDeck) and then it renders those objects in the html. Here is the javascript. The problem I am having is, while everything is working, the only thing that is not is the filteredWordsForDeck. It is not updating when the specificIndices is updated. The change is being reflect in the console although not in the html.

Any help would be so amazing as I have not been able to find a solution.

TLDR: Why is filteredWordsForDeck not updating when specificIndices changes.

//Words Data Set
//loaded in from vuex store.js 
const wordsForDeck = ref([]);
const alphaSorted = ref(false);
//indices that will be read through wordsForDeck
const specificIndices = ref([]);

// Function to generate indices array based on the length of wordsForDeck
const generateIndices = () => {
    specificIndices.value = Array.from({ length: wordsForDeck.value.length }, (_, i) => i);
};

// Watch for changes in the Vuex store's deckEntries
watchEffect(() => {
      // Access the words and definitions as an array from the store
    const wordsAndDefinitionsArray = store.state.deckEntries[index.value] ? 
                                     store.state.deckEntries[index.value].words : [];
   // Assign the array to the ref variable
    wordsForDeck.value = wordsAndDefinitionsArray;
    generateIndices(); 
});


//filtered words reads list at specified indices
const filteredWordsForDeck = computed(() => {
    return wordsForDeck.value
        .map((word, index) => ({ word, index }))  
        .filter(item => specificIndices.value.includes(item.index));

});

//Alphabetical sorting

//structure of ALPHABETICAL SORT
//wordsForDeck is rendered to html based on the order its indices
//array with original indices of all the words is created (this array contains the order in which they were created)
//when the sorta alpha is called, the indices are rearranged in the array to follow the alphabetical orders of the first word
//the array of indices that wordsForDeck reads changes based on whether alphaSorted is true or false

const sortAlpha = () =>{

    if (!alphaSorted.value){
      
        //sort indices based on alphabetical order
        const indexedWords = wordsForDeck.value.map((w, index) => ({ index, word: w.word }));
        indexedWords.sort((a, b) => a.word.localeCompare(b.word));
        specificIndices.value = indexedWords.map(iw => iw.index);
 
        //indices array now holds the alphabetically sorted arrays
        console.log(specificIndices.value);

        alphaSorted.value = !alphaSorted.value;

    } else {
        generateIndices();

        console.log(specificIndices.value);

        alphaSorted.value = !alphaSorted.value;

    }
}

Here is the html

        <div v-for="(word, index) in filteredWordsForDeck" :key="index" class = "w-full h-auto bg-white flex flex-row p-2 rounded-lg border justify-between" >
            <div class = "w-1/3 h-auto break-word text-left">
                <h class = "text-base text-gray-400">{{ index + 1 }}</h>
                <h class = "text-xl text-gray-600 w-8 relative left-4">{{ word.word.word }}</h>
            </div>
            <div class = "w-1/3 h-auto break-word">
                <p class = "text-base text-gray-400 mt-1">{{ word.word.definition }}</p>  
            </div>
        </div>

JavaScript Coding Challenge Objects

I’m new to coding so please forgive me it this is simple and any bad code. The question is:

Here’s an example problematic kitchen

const kitchen = {
  hasFridge: true,
  favouriteAppliance: 'KeTtlE',
  food: 'eGgS',
  shelvesInCupboards: 3,
  shelvesNotInCupboards: 2,
  petName: 'RhuBarB',
  hoover: 'DysOn'
};

To sort out our kitchen:

  1. Fix the jumbled string values – replace them all with versions that are all lowercase
  2. Remove the hoover property – hoovers don’t belong in the kitchen
  3. We only need to know the total number of shelves. If shelvesInCupboards and/or shelvesNotInCupboards are present, delete these keys
  4. Add a key of totalShelves which is equal to the sum of the values that were under shelvesInCupboards and shelvesNotInCupboards.

A fixed-up version of the above example kitchen should look like this, though remember that object properties are not ordered, so it doesn’t matter if your properties appear to be in a different order.

const kitchen = {
  hasFridge: true,
  favouriteAppliance: 'kettle',
  food: "eggs",
  petName: 'rhubarb',
  totalShelves: 5
};

The preset code is:

function sortTheKitchen(kitchen) {

    // Don't change the code below this line
    return kitchen;
}

I’ve gotten up to here so far but I am confused about the how to tackle parts 3 and 4 of sorting out the kitchen.

function sortTheKitchen(kitchen) {

    for (let key in kitchen) {
        if (typeof kitchen[key] === 'string') {
            kitchen[key] = kitchen[key].toLowerCase();
        }
    }

    delete kitchen.hoover;
    kitchen.totalShelves = (kitchen.shelvesInCupboards + kitchen.shelvesNotInCupboards);
    delete kitchen.shelvesInCupboards;
    delete kitchen.shelvesNotInCupboards;

    return kitchen
}

Thanks for any help you can provide.

Problems on a website on iOS devices when passing JSON data

My webapp is working on the desktop and on Android devices, but I tested it on two IOS devices and it no longer works, a few days ago it was also working normally on IOS devices, has there been an update? The problem is the following, when passing data as an argument in a function in console.log on Chrome on IOS (I’ve already tested Safari and other browsers) it just stops at the line where I put a console.log to debug, it doesn’t execute the line : var items = dados.itens , however if I put a console.log(dados.itens) make a copy of the object that is returning on the desktop and insert it manually in the “items” variable then yes it works on IOS.

async function getItens(dados) { 
    console.log('test debbuger') 
    var itens = dados.itens

What is the best facebook-like mentions plugin?

I have seen many posts from years ago about adding an @ mentions system into text boxes or textareas, I was wondering if there are any good ones created within the past couple years (as opposed to 10-15 years ago). The ones I have looked over are okay, but not very sophisticated, all created 2015 or earlier.

For me, it can be in plain javascript or jQuery, it can work within a text box or could be just in a contenteditable div. It could also combine @ mentions and # tags, that would just be a bonus.

What are the latest and greatest in mention plugins? My site is built on javascript/php/mySql, not that that should matter.

I have resisted trying to implement the ones I found because none of them seemed all that awesome.