Search results

Add item in between in DropDownList in JavaScript (ES5) DropDownList control

06 Jun 2023 / 1 minute to read

You can add item in between based on item index. If you add new item without item index, item will be added as last item in list.

The following example demonstrate how to add item in between in DropDownList.

Source
Preview
index.js
index.html
Copied to clipboard
var sportsData = [
    { Id: 'game1', Game: 'Badminton' },
    { Id: 'game2', Game: 'Football' },
    { Id: 'game3', Game: 'Tennis' }
];
//initiate the DropDownList
var dropDownListObject = new ej.dropdowns.DropDownList({
    // bind the sports Data to datasource property
    dataSource: sportsData,
    // maps the appropriate column to fields property
    fields: { text: 'Game', value: 'Id' },
    //set the placeholder to DropDownList input
    placeholder: "Select a game"
});
//render the component
dropDownListObject.appendTo('#ddlelement');
 
// add item at first
document.getElementById('first').onclick = () => {
    dropDownListObject.addItem({ Id: 'game0', Game: 'Hockey' }, 0);
};
// add item in between
document.getElementById('between').onclick = () => {
    dropDownListObject.addItem({ Id: 'game4', Game: 'Golf' }, 2);
};
// add item at last
document.getElementById('last').onclick = () => {
    dropDownListObject.addItem({ Id: 'game5', Game: 'Cricket' });
};
Copied to clipboard
<!DOCTYPE html><html lang="en"><head>
            
    <title>Essential JS 2 DropDownList</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Typescript UI Controls">
    <meta name="author" content="Syncfusion">
    <link href="styles.css" rel="stylesheet">
   <link href="//cdn.syncfusion.com/ej2/21.2.3/ej2-base/styles/material.css" rel="stylesheet">
    <link href="//cdn.syncfusion.com/ej2/21.2.3/ej2-inputs/styles/material.css" rel="stylesheet">
    <link href="//cdn.syncfusion.com/ej2/21.2.3/ej2-dropdowns/styles/material.css" rel="stylesheet">
    
    
<script src="https://cdn.syncfusion.com/ej2/21.2.3/dist/ej2.min.js" type="text/javascript"></script>
</head>
<body>
    
    <div id="container" style="margin:0 auto; width:250px;">
        <br>
        <input type="text" id="ddlelement">
 
    <div style="padding: 50px 0">
      <button id="first" class="e-control e-btn"> add item (Hockey) in first</button>
    </div>
    <div style="padding-left: 50px 0">
      <button id="between" class="e-control e-btn"> add item (Golf) in between</button>
    </div>
    <div style="padding: 50px 0">
      <button id="last" class="e-control e-btn"> add item (Cricket) in last</button>
    </div>
</div>


<script>
var ele = document.getElementById('container');
if(ele) {
    ele.style.visibility = "visible";
 }   
        </script>
<script src="index.js" type="text/javascript"></script>
</body></html>