How to Link an HTML Button With a Drop-Down Box

Site visitors usually click drop-down boxes to open them. Developers place these compact controls, also known as select boxes, on Web pages to save space. Until a user clicks a drop-down box, it only occupies one row on a Web page, even though it may contain hundreds of items. If you would like give users the ability to open and close a drop-down box using an HTML button, link these two controls using a JavaScript function.

Instructions

    • 1

      Launch an HTML editor or any text editor, and open one of your HTML documents.

    • 2

      Add the code shown below to the document's body section:

      <select id="dropDownBox1">

      <option>A</option>

      <option>B</option>

      <option>C</option>

      <option>D</option>

      </select>

      <input type="button" value="Open Drop Down" onclick="openDropdown('dropDownBox1', '3')" />

      This code creates a drop-down box and a button. When you click the button, it calls a JavaScript function named openDropdown. The button also passes the drop-down box's id value to the function along with the number 3.

    • 3

      Add the following JavaScript code to your document's head section:

      function openDropdown(dropDown, size) {

      var dropDownObject = document.getElementById(dropDown);

      dropDownObject.size = size;

      }

      This function -- called by the button -- obtains a reference to the drop-down box and sets its size value to the size passed to the function in the argument list.

    • 4

      Save the document, and launch your browser. Open the document in the browser. The drop-down box appears above the button on the Web page.

    • 5

      Click the button. The code runs and opens the drop-down box automatically.

Tips & Warnings

  • Note that the button's click event passes the number 3 to the JavaScript function, even though four items exist in the drop-down box. When calling the function on a real Web page, pass any value you like. You do not have to pass a value that is equal to the number of items in the drop-down box. You could also add another button that closes the drop-down box when clicked. Create such a button by duplicating the button code described in the previous steps and passing zero to the JavaScript function instead of 3.

Related Searches:

References

Resources

Comments

Related Ads

Featured