Submit form and go to link from dropdowns

I have a simple form with 2 drop downs, I need to post the value from the first drop down and go to the link in the second drop down (where the first drop down value will be shown). I can get either of them to work (one with some javascript) but not both at the same time?

<form action="" method="POST" id="carform">

<select name="carlist">
  <option value="new">New</option>
  <option value="used">Used</option> 
</select> 

<select name="link">
  <option value="car/volvo.php">Volvo</option>
  <option value="car/saab.php">Saab</option>
</select> 

<input type="submit">

</form>

Answers


Keeping it simple for the lesson. You are searching for the JavaScript & AJAX. First you need to create a page where the options will be created dynamically. For the example ajax.php:

<?php
$car_state = $_POST['state'];
/* depending on your data format you need to filter the $car_state or make them e.g.
 * 1 for new and 2 for used and run intval($_POST['state'])
 * the best would be prepared statements but its your choice
 */

#operations on your data
foreach($data as $row)
{
    echo '<option value="'.$row->url.'">'.$row->name.'</option>';
}
?>

Then you need to use the onchange event. You can use jQuery to keep it simple but its not the only choice. So adding this to your HTML format.

<script type="text/javascript">
$('select[name=carlist]').change(function() {
    var state_value = $(this).val();
    if(state_value != "")
    {
        $.post('ajax.php', {state: state_value}, function(data) {
            $('select[name=link]').html(data);  
        });
    }
}); 
</script>

Need Your Help

How to use a tab widget in Android?

android

Can anyone show me how to make a tab widget in Android?

Free shipping on google checkout in magento

magento google-checkout

I am using magento 1.7.0.2 and Google Checkout. When want to use Flat rate, Free Shipping over $75 and 10% shipping between $68 - $75.