Search code examples
javascriptfunctionselectonchange

Function which enables to select different background color of each element from different color in javascript?


I have a project which is the note-taking website. When someone adds a note it is stored in local storage in the form of an array and a Javascript function works which calls the stored element and runs for each on the elements. Here is the Javascript code:

function showNote2() {
    console.log("Show");
    let note = localStorage.getItem("notes");
    if(note == null){
        noteData = []
        // message.innerText = "Please Add a Note"
    }
    else{
        noteData = JSON.parse(note);
    };
    let showBox = "";
    noteData.forEach(function show(element, index) {
        showBox += `<div class="noteCard my-2 mx-2 card" id="card4" style="width: 18rem;">
        <select id="mySelect" class="clr-btn" style="text-align:center" onchange="change_color()">
        <option id="bckgrnd-clr" value="white">Background Color</option>
        <option id="red" value="Red">Red</option>
        <option id="green" value="Green">Green</option>
        <option id="blue" value="Blue">Blue</option>
        </select>
                <div class="card-body" id="card3">
                  <h5 class="cardtitle">Note
                  ${index + 1}
                  </h5>
                  <p class="card-text"> 
                  ${element}
                  </p>
                  <button id="${index}" onclick="deleteNote(this.id)" class="btn btn-primary">Delete Note</a>
                </div>
              </div>   `
            })
              let showNote3 = document.getElementById("notes2");
              if(noteData.length != 0){
                  showNote3.innerHTML = showBox;
              }else{
                  showNote3.innerHTML = "Please add a Note"
              }
}

In the above code, select gives us the option to choose a color for the note, now I want to add a function to onchange which can help me choose a different color for different notes. The function I used was working only on the first-note and setting the color of all notes according to the selected option of first-note. The color will be applied on class with card-body

I am building this for practice in Javascript. Any hints would be appreciated, as this is something new for me Update: This is the solution I applied after getting the idea from the comments.

function change_color(index) {
    let note = localStorage.getItem("notes");
    if(note != null ){
        let colorApply = document.getElementById("card3")
        let elm1 = document.getElementById(index)
        let color = elm1.options[elm1.selectedIndex].value;
        document.colorApply.style.backgroundColor = color;
    }
    else{
        `Note is Empty`
    }

Now this is the error i am getting at color

"Cannot read properties of null (reading 'options')" Any help would be appreciated?


Solution

  • See the working snippet. :)

    In your loop, change code like this:

    let elm1 = document.getElementById(index)
    

    to

    let showNote3 = document.getElementById(`card${index}`);
    let colorApply = document.getElementById(`card${index}`)
    let elm1 = document.getElementById(`mySelect${index}`)
    

    and in your HTML

    `<div class="noteCard my-2 mx-2 card" id="card${index}" ...` />
    `<select id=`mySelect${index}` class="clr-btn" style="text-align:center" onchange="change_color()">`
    

    Also when you have the element, you do not need to use document

    // -> document.colorApply.style.backgroundColor = color;
    colorApply.style.backgroundColor = color;
    

    Finally, you need to send the index of the note into your change_color function.

    onchange="change_color(${index})"
    

    function showNote2() {
      console.log("Show");
      let note = null // localStorage.getItem("notes");
      if (note == null) {
        noteData = ['My Note 1', 'My Note 2']
        // message.innerText = "Please Add a Note"
      } else {
        noteData = JSON.parse(note);
      };
      let showBox = "";
      noteData.forEach(function show(element, index) {
        showBox += `
        <div class="noteCard my-2 mx-2 card" id="card${index}" style="width: 18rem;">
                <select id="mySelect${index}" class="clr-btn" style="text-align:center" onchange="change_color(${index})">
                <option id="bckgrnd-clr" value="white">Background Color</option>
                <option id="red" value="Red">Red</option>
                <option id="green" value="Green">Green</option>
                <option id="blue" value="Blue">Blue</option>
                </select>
                <div class="card-body" id="cardbody${index}">
                          <h5 class="cardtitle">Note ${index + 1}</h5>
                          <p class="card-text"> 
                          ${element}
                          </p>
                          <button id="btn${index}" onclick="deleteNote(this.id)" class="btn btn-primary">Delete Note</a>
                        </div>
                      </div>   
                      `
      })
      let showNote3 = document.getElementById("note");
      if (noteData.length != 0) {
        showNote3.innerHTML = showBox;
      } else {
        showNote3.innerHTML = "Please add a Note"
      }
    }
    
    function change_color(index) {
      let note = noteData[index] // localStorage.getItem("notes");
      if (note != null) {
        let colorApply = document.getElementById(`card${index}`)
        let elm1 = document.getElementById(`mySelect${index}`)
        let color = elm1.options[elm1.selectedIndex].value;
        colorApply.style.backgroundColor = color;
      } else {
        console.log(`Note is Empty`)
      }
    }
    
    showNote2()
    <h1>Notes</h1>
    <div id='note' />
    <button onclick='note' />