dropdown chatgpt
by Satheesh Kumar
HTML
<select data-plugin="myElement" id="mySelect">
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
JavaScript
(function($) {
// Define the plugin
$.fn.selectPlugin = function(options) {
// Default settings
var settings = $.extend(
{
onChange: null
},
options
);
// Plugin methods
var methods = {
init: function() {
return this.each(function() {
var $select = $(this);
// Bind change event
$select.on('change', function() {
var selectedValue = $select.val();
var selectedText = $select.find('option:selected').text();
// Call the onChange callback function if provided
if (typeof settings.onChange === 'function') {
settings.onChange.call(this, selectedValue, selectedText);
}
});
});
},
setValue: function(value) {
return this.each(function() {
var $select = $(this);
$select.val(value);
});
},
getValue: function() {
var $select = $(this);
return $select.val();
},
updateOptions: function(options) {
var $select = $(this);
$select.empty();
// Add new options
for (var i = 0; i < options.length; i++) {
var option = options[i];
$select.append($('<option></option>').attr('value', option.value).text(option.text));
}
return $select;
}
};
// Plugin events
var events = {
customEvent: 'customEvent'
};
// Initialize the plugin
methods.init.call(this);
// Expose plugin methods and events
return {
setValue: methods.setValue,
getValue: methods.getValue,
updateOptions: methods.updateOptions,
customEvent: events.customEvent
};
};
})(jQuery);
// Initialize the plugin
var selectElement = $('#mySelect').selectPlugin({
onChange: function(value, text) {
console.log('Selected value:', value);
console.log('Selected text:', text);
}
});
/* // Define new options
var...