I thought to write some JavaScript wrapper code without using any client-side framework to deal with HTML controls efficiently, with the help of method and properties, in a similar way to how a Windows developer does in the Windows form application without knowing the inner complexities.
Though the jQuery framework provides lots of methods and properties to deal with the HTML controls, at some point the developer has to remember some of the attributes to supply as an argument or parameter to jQuery methods or properties. For example, to add a new element to the dropdown or with a text value pair, or getting a value for a given index position, etc., which is not a bit of easy work. So in this attempt of writing code, I just focused on dealing with dropdown control, and I believe the reader will have enough of an idea about writing code in JavaScript, and also how to write methods and properties and classes.
Here's the wrapper methods and properties
- var arj = {
-
- Select: function (ElementID)
- {
- this.SelectedIndex = function ()
- {
- var ctrl = document.getElementById(ElementID);
- return ctrl.selectedIndex;
- }();
- this.SelectedText = function ()
- {
- var ctrl = document.getElementById(ElementID);
- if (ctrl.selectedIndex >= 0)
- {
- return ctrl.options[ctrl.selectedIndex].text;
- }
- else
- {
- return "";
- }
- }();
- this.SelectedValue = function ()
- {
- var ctrl = document.getElementById(ElementID);
- if (ctrl.selectedIndex >= 0)
- {
- return ctrl.options[ctrl.selectedIndex].value;
- }
- else
- {
- return "";
- }
- }();
- this.Length = function ()
- {
- var ctrl = document.getElementById(ElementID);
- return ctrl.options.length;
- }();
- this.GetText = function (index)
- {
- var ctrl = document.getElementById(ElementID);
- return ctrl.options[index].text;
- };
- this.GetValue = function (index)
- {
- var ctrl = document.getElementById(ElementID);
- return ctrl.options[index].value;
- }
- this.AddItem = function (data)
- {
- var ctrl = document.getElementById(ElementID);
- var option = document.createElement("option");
- option.text = data;
- ctrl.add(option);
- return true;
- };
- this.AddValueItem = function (data, value)
- {
- var ctrl = document.getElementById(ElementID);
- var option = document.createElement("option");
- option.text = data;
- option.value = value;
- ctrl.add(option);
- return true;
- };
- this.RemoveItem = function (index)
- {
- var ctrl = document.getElementById(ElementID);
- ctrl.remove(index);
- };
- return this;
- }
- }
How to use above given method is shown below:
- Adding an Item to dropdown,
- arj.Select("dropdownid").AddItem(“Hello”);
- Adding an item with value,
- arj.Select("dropdownid").AddValueItem(“Hello”, 1001);
- Get value for given index position,
- arj.Select("dropdownid ").GetValue(1);
- Get text for given index position,
- arj.Select("dropdownid").GetText(1);
The attached code is fully-functional and ready to use with any existing project. Any feedback and suggestions are most welcome.