user2747249
user2747249

Reputation:

javascript delete a selected element in a select list

The HTML of the select list is:

<div class="textf_rechts">
<select style="height: 14em; width: 300px" size="10" name="hersteller">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select> </div>

I want to delete the sected element so I tried:

var select = document.getElementsByTagName('select').selectedIndex;
select.removeChild(select[select.selectedIndex]);

but it returns that select variable is undefined

Upvotes: 0

Views: 1460

Answers (2)

Ramdas Nair
Ramdas Nair

Reputation: 278

In this code:

var select = document.getElementsByTagName('select').selectedIndex;
select.removeChild(select[select.selectedIndex]);

...you're setting select to be undefined, because you're trying to access the selectedIndex property on a NodeList. NodeLists don't have a selectedIndex property. Then you try to call removeChild on undefined.

It should be more like this:

var select = document.getElementsByTagName('select')[0];
if (select && select.selectedIndex >= 0) {
    select.removeChild(select[select.selectedIndex]);
}

We get the first select box, then if there is one and it has something selected, we remove that selected item.

Live Example | Source

Upvotes: 2

Anjith K P
Anjith K P

Reputation: 2158

Try this

 <div class="textf_rechts">
        <select id ="select" style="height: 14em; width: 300px" size="10" name="hersteller">
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
            <option>5</option>
        </select> 
    </div>

Js

var element = document.getElementById("select");
element.options[element.selectedIndex].remove();

Upvotes: 0

Related Questions