Why wont this Javascript code work

HTML:



<button onclick="handlers.changeItem()">Change to do </button>
  <input type="number" name="text" id="text1">
  <input type="text" name="text" id="text2">


JS:

mitchToDoList = {
// Change an item, main method
changeItem: function(position, newValue){
  this.listItems[position] = newValue
  this.displayItems()
} 
}

// attaching to the html buttons, but not changing?

handlers = {
changeItem: function(){
var changePosition = document.getElementById('text1');
var changeValue = document.getElementById("text2");

mitchToDoList.changeItem(changePosition.valueAsNumber, changeValue.value);

changePosition.value = ""
changeValue.value = ""
}
}


Any ideas? Please if we could just focus on the code at hand, I want to understand why this specific instance isn’t working. Thanks.

In the changeItem() function you reference 'listItems; and ‘displayItems()’ which aren’t defined in the js code provided here.

Do you have more code from this project to share?

1 Like

Sure thing. I will post it.

Thanks Dobs, I will do my best to review and provide feedback to your code.

1 Like

Here it is, github and live link.

github: https://github.com/dobs1993/ToDoListWithJS
live link: https://naughty-archimedes-c7fc94.netlify.app/

Thanks AidanDev

I cant seem to find the bug.

I thought it was originally on line 92 of the JS code. Since then, I have back tested though and realized the problem is coming even without the buttons involved. Even just running in the console and running the method on line 30 / /changeItem() it is still deleting the first item from my to do list.

running mitchToDoList.changeItem() method still deletes the first item from the to do list without even including the buttons. However the new code I added is the code on line 92, so I am not sure how this made any change to the code earlier in the file.

Let me know if you find anything that could be the result.

Thanks

Anyone have any luck?

You are just overwriting the todo object with a string value, you want to set the newItem property to the new value.

What you have:

changeItem: function(position, newValue) {
  this.listItems[position] = newValue;
  this.displayItems();
}

Update the property value:

changeItem: function(position, newValue) {
  this.listItems[position].newItem = newValue;
  this.displayItems();
}
3 Likes

Wow, I cant believe I missed that. I feel silly. Thanks for pointing that out. I reverse engineered it back to that line but didn’t notice that. Thank you.

Well spotted Isajorg

1 Like