HungryDB
HungryDB

Reputation: 575

How to display tables using dropdown box

I am trying to display two tables using dropdown box choices.

I'm using this JS code. Here's FIDDLE

 function change_tbl(dhi)
           {
                      if(dhi=='')
                     {
                            return;
                     }
                     $('#tbl_div div').css('display','none');
                     $('#'+dhi).css('display','block');
          }

but it isn't working. How? I need first table to display on load. (Means first table should be default choice.) Any solutions?

Upvotes: 2

Views: 7612

Answers (2)

Awlad Liton
Awlad Liton

Reputation: 9351

Demo : http://jsfiddle.net/4K9hM/3/

Html:

<select id="tt" >
    <option value="">select table</option>
    <option value="tb1">table 1</option>
    <option value="tb2">table 2</option>
</select>
<div id="tbl_div">

    <div id="tb1">
        <table border="1">
            <tr><td>1</td><td>2</td></tr>
            <tr><td>1</td><td>2</td></tr>
        </table>
    </div>

    <div id="tb2">
       <table border="1">
           <tr><td>2</td><td>2</td></tr>
           <tr><td>2</td><td>2</td></tr>
       </table>
    </div>
</div>

Js:

$(document).ready(function(){
        $("#tt").change( function ()
        {
            dhi = $("#tt").val();
             if(dhi=='')
            {
                return;
            }
            $('#tbl_div div').css('display','none');
            $('#'+dhi).css('display','block');
        });
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You need to call the function in onchange() like

<select onchange="change_tbl(this.value)">
    <option value="">select table</option>
    <option value="tb1">table 1</option>
    <option value="tb2">table 2</option>
</select>

Demo: Fiddle

Also in the fiddle there are few other problems like

  1. jQuery was not included
  2. since change_tbl is used in an inline handler you need to declare it in the global scope - select No Wrap Head/Body in the second dropdown in the left panel

Use a jQuery event handler like

<select id="table-select">
    <option value="">select table</option>
    <option value="tb1" selected>table 1</option>
    <option value="tb2">table 2</option>
</select>

then use a .change() handler to register the change event handler

jQuery(function () {
    $('#table-select').change(function () {
        $('#tbl_div > div').css('display', 'none');
        if (this.value) {
            $('#' + this.value).css('display', 'block');
        }
    }).change(); //this is used to trigger a manual change handler initially so that the state is properly set on page load
})

Demo: Fiddle

Also read: Document Ready, trigger handler, change() handler, id-selector

Upvotes: 3

Related Questions