Adding DropDown or ComboBox dynamically using jQuery
This tutorial will show you how we can create combobox using jQuery.
We will also alert the value when we select the item from the combobox or dropdown.<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
//create a variable which holds key/value pairs
var data = { 'Country0': 'India', 'Country1': 'Sri Lanka', 'Country2': 'USA', 'Country3': 'Australia', 'Country4': 'Newzeland'};
//create a variable that holds select tag with an id="combo", you can also put 'class' attribute instead of combo
var s = $('<select id="combo" />');
//iterate through each key/value in 'data' and create an option tag out of it
for(var val in data) {
$('<option />', {value: val, text: data[val]}).appendTo(s);
}
//clicking on the button will display the combobox or dropdown - clicking on the
//button it will append the dropdown to a paragraph
$("#addCombo").on('click', function() {
s.appendTo('p');
});
//when we select an item from dropdown or combobox then alert that value
$(document).on('change',"#combo", function(){
alert(this.value);
});
});
</script>
</script>
</head>
<body>
<button id="addCombo">Add Combo</button>
<p/>
</body>
</html> Output
Thanks for reading.

No comments