i'm trying to get my generated button id when I click it, to select and manipulate own parent div.
$(this).attr("id") and this.id are returning undefined or k.fn.init.
What am I missing, please?
JS:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
// functions
let taskCounter = 0;
let addOne = () => {
let userStr = document.getElementById("userText").value;
let nextItem = taskCounter;
$("#toDoList ul").append('<div class="item-'+nextItem+'"><li>'+userStr+'</li><input id="btn-'+nextItem+'" type="button" value="Complete Task" onclick="taskDone()"></div>');
taskCounter = taskCounter + 1
}
let taskDone = () => {
let selectTest = $(this).attr("id");
console.log(selectTest);
return selectTest;
}
</script>
HTML:
<html>
<body>
<input id="userText" type="text" placeholder="Enter Task Here">
<input id="addToList" type="button" value="Add Task" onclick="addOne()">
<h2>To Do</h2>
<div id="toDoList">
<ul>
</ul>
</div>
<h2>Done</h2>
<div id="DoneList">
<ul>
</ul>
</div>
</body>
</html>
you can pass the element in params:
// functions
let taskCounter = 0;
let addOne = () => {
let userStr = document.getElementById("userText").value;
let nextItem = taskCounter;
$("#toDoList ul").append('<div class="item-' + nextItem + '"><li>' + userStr + '</li><input id="btn-' + nextItem + '" type="button" value="Complete Task" onclick="taskDone(this)"></div>');
taskCounter = taskCounter + 1
}
function taskDone(el) {
let selectTest = el.getAttribute("id")
console.log(selectTest);
//return selectTest;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<input id="userText" type="text" placeholder="Enter Task Here">
<input id="addToList" type="button" value="Add Task" onclick="addOne()">
<h2>To Do</h2>
<div id="toDoList">
<ul>
</ul>
</div>
<h2>Done</h2>
<div id="DoneList">
<ul>
</ul>
</div>
</body>
</html>
Use a regular function definition instead of an arrow function. An arrow function changes the context of this. So with let taskDone = () => {...} and you try to access this, it's not referring to the element you clicked. Instead, try let taskDone = function () {...}.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With