I'm trying to make a 'CRUD' in pure Javascript, it's almost done, the only thing that I need is preparing the inputs with the value of <li>
, to do it, I'd like to add an onclick
event in a checkbox that is created dynamically in the function insert()
, but everytime I click the checkbox nothing happens.
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function(){
btnInsert = document.getElementById("btnInsert");
btnEdit = document.getElementById("btnEdit");
btnDelete = document.getElementById("btnDelete");
vname = document.getElementById("tbName");
ul = document.getElementsByTagName("ul")[0];
btnInsert.onclick = insert;
btnDelete.onclick = remove;
}
function insert(){
li = document.createElement("li");
li.innerHTML = vname.value;
li.innerHTML += " <input type='checkbox' onclick='select()' value='Select' /> Update";
ul.appendChild(li);
vname.value = "";
}
function select(){
alert("Checked");
}
function remove(){
var lis = document.getElementsByTagName("li");
for(i = 0; i<lis.length; i++){
lis[i].onclick = function(){
this.remove();
}
}
}
</script>
</head>
<body>
<label for="tbName">Name: </label>
<input name="tbName" id="tbName"/><br /><br />
<button id="btnInsert">Insert</button>
<button id="btnEdit">Edit</button>
<button id="btnDelete">Delete</button>
<br /><br />
<ul>
</ul>
</body>
</html>
It seems the name select
is causing conflict since I could get your code working with the following changes:
HTML
li.innerHTML += " <input type='checkbox' onclick='sel()' value='Select' />Update";
Javascript
function sel(){
alert("Checked");
}
Further tests show that if we log the contents of the function with:
li.innerHTML += " <input type='checkbox' onclick='console.log(select.toString)' value='Select' />Update";
the console shows the following
function select() { [native code] }
So my guess is that select
is the name of a function already defined by the browser, hence why you can't use it as a name for your functions.
In short , your code triggers another select
function, not the one you defined in your source code.
The OP doesn't want it to fire on the LI
, he wants it to fire on the checkbox
!
Give your dynamic checkbox an ID value like chkBox1
. Now after you have appended it to the document, you can call it with:
var thechkBox=document.getElementById("chkBox1");
Now you can hit thechkBox
with:
thechkBox.addEventListener("click", itfired); //itfired is the script that captures the click event.
That is one of many Events you would then have access to ( https://www.w3schools.com/js/js_htmldom_events.asp )!
If you needed the dynamic checkbox to perform a function "on"click!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.