theHussle theHussle - 2 months ago 5
Javascript Question

Setting a default value when populating dropdown with Ajax

I've some code I've been working on, which uses AJAX to generate a second dropdown based on information in the database.

For example
If you select BMW
it will populate the second list with all available BMW models, this is working correctly, but I would like one of the fields in the second drop down to remain SELECT, or ANY, so that they can search solely on car Make.

I've had a look online and the solutions seem very complicated for what I would hoped was a simple fix, I'm now stuck on how to fix the issue, should I just add a separate form for just make? Although this wouldn't be as user friendly.

<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<form id="fitment_search" action="gallery.php" method="GET">
<div class="col-sm-5">
<div class="col-sm-4">
<h5>Vehicle Make:</h5>
</div>
<div class="col-sm-8">
<div class="select">
<select name="make" onchange="get_model(this.value)">
<option value="make">SELECT</option>
<?php while ($row = mysqli_fetch_assoc($makeResult)) : ?>
<option
value="<?php echo $row['make']; ?>"><?php echo $row['make']; ?></option>
<?php endwhile; ?>
</select>
<div class="select__arrow"></div>
</div>
</div>
</div>
<div class="col-sm-5">
<div class="col-sm-4">
<h5>Model:</h5>
</div>
<div class="col-sm-8">
<div class="select">
<select name="model" id="fitment_model">
<option value="">SELECT</option>
</select>
<div class="select__arrow"></div>
</div>
</div>
</div>
<div class="col-sm-2">
<button type="submit" class="btn btn-default btn-sm btn-primary"><i
class="fa fa-pencil"></i> Search Now
</button>
</div>

</form>
</div>


Heres the code form the seperate php file.

$make=$_GET["make"];

$sql2 = "SELECT `model` FROM `fitment` WHERE `make` = '$make' ORDER BY `model` ASC";

$result = mysqli_query($db, $sql2);
?>

<select name="models"> <?php

while($row = mysqli_fetch_array($result)) { ?>

<option value="<?php echo $row['model']?>"><?php echo $row['model'] ?></option><?php

} ?>

</select>

Answer

just change:

<select name="models"> <?php

TO

<select name="models"> 
  <option value="" >Select</option>    
  <?php