简体   繁体   中英

how can we remove an item from SELECT list whose SIZE is not declared

How can we remove a selected item from SELECT whose SIZE is not declared, means acting as drop down list. using javascript

Here is a very nice article outlining how you can add/remove items to select list.

This is function to remove selected item (from site):

function removeOptionSelected()
{
  var elSel = document.getElementById('selectX');//selectX IS ID OF SELECT
  var i;
  for (i = elSel.length - 1; i>=0; i--) {
    if (elSel.options[i].selected) {
      elSel.remove(i);
      break;//As suggested in comments
    }
  }
}

THIS IS WHAT I WOULD HAVE DONE:

function RemoveOption(){
     $("#SelectId option:selected").remove();
}

Since you want to delete a single selected option, you could easily:

Remove the element using the select.remove function:

var el = document.getElementById('selectId');
el.remove(el.selectedIndex);

Or by DOM manipulation:

var el = document.getElementById('selectId');
el.removeChild(el.options[el.selectedIndex]);

Check an example here .

Doing it the jQuery way:

<html>
<head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $("#myButton").click(function(){
                    $("#mySelect option:selected").remove();
                });
            });
        </script>
</head>
<body>
    <select id="mySelect">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
        <option value="4">Four</option>
    </select>

    <input type="button" id="myButton" value="remove"/>
</body>
</html>

I know, nobody asked for jQuery, but IMHO nobody should DOM+JavaScript without jQuery anymore!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM