Reputation: 41
I need some help (under the code you can see what I need)
here is the code:
HTML
<input type="number" id="elementnr">
<button onclick="theFunction()">Remove it</button>
<p id="theElements"/>
JAVASCRIPT
<script>
var cars = ["Bentley", "Ferrari", "BMW", "Mercedes", "Lamborghini"];
document.getElementById("theElements").innerHTML = cars;
function theFunction() {
delete cars[3];
document.getElementById("theElements").innerHTML = cars;
}
</script>
Right now this code when you click the button it removes the 3rd element(Mercedes) because we gave that function but i wanted to know if there's any way to edit the code so when i type the number 4 in the textbox and click the button it removes the 4th element or if i type 2 on the textbox and click the button it removes the 2nd element etc.
Upvotes: 0
Views: 47
Reputation: 1873
You could read 'value' property of Input HTML element.
Using delete
operator on an Array element in JS does not remove given element, but sets its value to undefined
, thus array's length remains the same and it can lead to many bugs.
Usually splice
function is used to remove something from an array in JavaScript.
var cars = ["Bentley", "Ferrari", "BMW", "Mercedes", "Lamborghini"];
var carsList = document.getElementById("carsList");
var elementIndex = document.getElementById("elementIndex");
function removeElementByIndex() {
cars.splice(elementIndex.value,1);
setHtml(carsList, cars);
}
function setHtml(node, content){
node.innerHTML = content;
}
setHtml(carsList, cars);
<input type="number" id="elementIndex">
<button onclick="removeElementByIndex()">Remove it</button>
<p id="carsList"></p>
Upvotes: 1