Combobox with Click Event in JavaScript

In this tutorial, we will going to create a program that has the Combobox control with its click event using JavaScript. Now let's start this tutorial! 1. Open Notepad++. Create a new file and name it as comboboxJS.html. 2. Create open and close tags for HTML, Title, and the Body. 3. Now, in the body, have this code below:
  1. <form action="" method="post" onsubmit="return validate()">
  2. <span id="cty">Country: <select name="country" id="country">
  3. <option value="">Choose a country</option>
  4. <option value="Australia">Australia</option>
  5. <option value="Great Britain">Great Britain</option>
  6. <option value="India">India</option>
  7. </select>
  8. </span>
  9. <input type="submit" value="Submit" />
  10. </form>
In the code above, we have created a form that has its method post and has a button with the code <input type="submit" value="Submit" />. If the user presses the button, it will return to the function validate (that's the next step). Then we created a label using the span tag <span id="cty">Country: <select name="country" id="country">. This span is used to include the combobox inside. To create a combobox, we call the option tag and has the three values of a country such as Australia, Great Britain, and India. 4. The next step will have the clickable function of the button to choose among the items in the combobox. Have the code below:
  1. <script type="text/javascript">
  2. function validate() {
  3. var combo1 = document.getElementById("country")
  4. if(combo1.value == null || combo1.value == "") {
  5. alert("Please select a country");
  6. document.getElementById("cty").style.border = "2px solid red";
  7. return false;
  8. }
  9. else {
  10.  
  11.  alert("Selected Country is:" + combo1.value);
  12. }
  13. }
  14. </script>
In the code above, we have created a function named validate. This is to have the combobox validation when choosing a country. Our variable combobox is equal to the id of the country that we have in the span tag in step 3. If combobox value is null or empty, then it will alert the page to choose the country and it will have the border of the combobox turned to red. Otherwise, it will display the three values of the combobox to those specific countries. Output: out out out Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment