How To Update The Selected LI From An UL Using Javascript
In This Javascript Tutorial we will See How To Edit The Selected <li> Text Value Using Input Text On Button Click Event And Array To Get LI Index In JS And Netbeans Editor .
Project Source Code:
<!DOCTYPE html>
<html>
<head>
<title>javascript: edit selected LI</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="text" id="txt"><button onclick="editLI()">Edit</button>
<ul id="list">
<li>JS</li>
<li>PHP</li>
<li>Java</li>
<li>C#</li>
<li>C++</li>
<li>HTML</li>
<li>CSS</li>
</ul>
<script>
var items = document.querySelectorAll("#list li"),
inputText = document.getElementById("txt"),
tab = [], liIndex ;
// populate tab with li value
for(var i = 0; i < items.length; i++)
{
tab.push(items[i].innerHTML);
}
// get selected li into text fields and get the index
for(var i = 0; i < items.length; i++)
{
items[i].onclick = function(){
inputText.value = this.innerHTML;
liIndex = tab.indexOf(this.innerHTML);
console.log(this.innerHTML +" INDEX = " + liIndex);
};
}
function editLI()
{
items[liIndex].innerHTML = inputText.value;
// clear array
tab.length = 0;
// fill array
for(var i = 0; i < items.length; i++)
{
tab.push(items[i].innerHTML);
}
}
</script>
</body>
</html>
OUTPUT: