Button event is only selecting the first class. (Jquery)

Viewed 36

I am trying to select the saveBtn class on each button so that when I click it it saves it into local storage. However it is only saving the first instance of the selected class. Can anyone help?

html:

  <div class="hour-container" id="8am">
    <div class="hour"> 8 AM </div>
    <textarea class="text-content"></textarea>
    <button class="btn saveBtn"><i class="fas fa-save"></i></button>
  </div>

js:

// Function to save the users input to the text area
function saveText() {
    var textContent = $(".saveBtn").siblings(".text-content").val();
    var hour = $(".saveBtn").parent().attr("id");
    localStorage.setItem(hour, textContent);
    console.log(textContent);
}

// Call saveText on save button click
$(".saveBtn").on("click", saveText);
1 Answers

In the event handler, the searching scope of $(".saveBtn") is the whole web page.

That means the reference point of all actions is referred to the beginning of the web page.

So, the function $(".saveBtn") always refer to the first element which has the saveBtn CSS class.

You may modify the saveText function as the following:

function saveText() {
    var textContent = $(this).siblings(".text-content").val();
    var hour = $(this).parent().attr("id");
    localStorage.setItem(hour, textContent);
    console.log(hour,textContent);
}

For my solution, the this refers to the element which has been clicked by a user, so the reference point of all actions is referred to the element which has been clicked, therefore it should be work fine.

Related