0

this is my code:

function newTodo() {
  const text = prompt('What needs to be done?').trim();
  if (!!text) {
    id += 1;
    const todoId = 'todo' + id;
    // checkbox
    const todoCheckbox = document.createElement('input');
    todoCheckbox.type = 'checkbox';
    todoCheckbox.id = todoId;
    todoCheckbox.classname = classNames.TODO_CHECKBOX;
    todoCheckbox.setAttribute('onclick', `handleCheck(${todoId})`);
   ...
  } else {
    alert('Please enter a valid todo');
  }
}

function handleCheck(todoId) {
  console.log('checked!', todoId);
}

but handleClick is logging the html element the function is attached to:

<input type="checkbox" id="todo2" onclick="handleCheck(todo2)">

I wanted to log the id only, so i am expecting it to be:

todo2

what am i doing wrong?

2
  • handleClick you mean handleCheck ? Commented Mar 6, 2019 at 7:54
  • not sure what you are passing to your function is a string. try to enclose it in single quotes <input type="checkbox" id="todo2" onclick="handleCheck('todo2')"> Commented Mar 6, 2019 at 8:05

2 Answers 2

1

Your handler:

onclick="handleCheck(todo2)"

attempts to reference a global variable named "todo2" and pass it to the handleCheck function. Because (confusingly) element IDs are automatically added to the global object, this results in the element you just created being passed to the function.

Surround the todoId in quotes instead, to ensure it gets passed as a string:

todoCheckbox.setAttribute('onclick', `handleCheck('${todoId}')`);

But, it would be significantly more elegant to add the handler properly using Javascript instead of an inline HTML attribute:

todoCheckbox.onclick = () => handleCheck(todoId);

Dynamic IDs are a code smell, though - they're rarely necessary. If you need data unique for each element, you might consider using data- attributes, or a Map.

Sign up to request clarification or add additional context in comments.

Comments

0

It should be <input type="checkbox" id="todo2" onchange="handleCheck(todo2)">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.