methuselah
methuselah

Reputation: 13206

Drop down live update in a form

How do you live update the content of drop down 2 based on the selection made in drop down 1 in a PHP based web form?

Would appreciate any code examples to work from.

Many thanks!

Upvotes: 0

Views: 1689

Answers (5)

Shad
Shad

Reputation: 15451

You are going to have to use AJAX, I would recommend jQuery's abstraction.

e.g.

<select id="sel1">
   <option value="1">1</option>
   <option value="2">2</option>
</select>
<select id="sel2">
</select>
<script type="text/javascript">
$('#sel1').change(funciton(){
   $.ajax({url: 'fetchSel2.php',
           data:{sel1:$('#sel1').val()},
           success:function(data){
               $('#sel2').html(data);
           }
          });
});
</script>

This presumes there is a 'fetchSel2.php' that is ready to serve the options for the second select.

e.g.

function getSecondOptions($sel1){
    $r=mysql_query(RELEVANT_QUERY);
    $opts='';
    if($r && mysql_num_rows($r)>0){
        while(list($label,$val)=mysql_fetch_row($r)){
            $opts.='<option value="'.$val.'">'.$label.'</option>';
        }
    }
    return $opts;
}

if(isset($_GET['sel1'])){
    echo getSecondOptions($_GET['sel1']);
}
exit;

Upvotes: 2

F21
F21

Reputation: 33391

You have these options:

  • Use AJAX if you don't want the form to refresh and update parts of the form.

  • If you don't want to use ajax and can bear with refreshing the whole form, you can capture the onChange event of the drop down using javascript.

  • If the user does not have javascript enabled, the above 2 methods will fail. Therefore, it is best to include a button users can click, which will ask the PHP side to rerender the form.

My personal preference is to use the last method as a fall back for those who do not have javascript enabled. Then use the first method (AJAX) to progressively enhance the form for those that have javascript.

Upvotes: 1

Korvin Szanto
Korvin Szanto

Reputation: 4501

I recently did this with jQuery http://jsfiddle.net/tBrXt/1/

Upvotes: 1

Bernesto
Bernesto

Reputation: 1436

What you are looking for is a cascading dropdown list. This is done using AJAX triggered in sequence by each dropdown. Here is an example via Google (http://codestips.com/php-ajax-cascading-dropdown-using-mysql/), note I'm not endorsing this link, it's just the first reasonable result.

Upvotes: 1

Bryan
Bryan

Reputation: 645

For live update, you need to use AJAX and require JS enabled browser. If the user-browser don't support JS or JS is disabled, the only option is to submit the form and reload the whole page with the updated option in the 2nd dropdown. If you want the JS code to perform AJAX, can you kindly tell me the JS library you want to use, so I can provide the code accordingly.

Upvotes: 1

Related Questions