0

I already have the first HTML select populated by the result of the first query.

Now what I need or want to do is put the results from the second query on a Json file (maybe) or an XML (don't care) and then using javascript (not jquery) populate the second HTML select based on the first HTML select option selected.

This is my current code:

    <?php
    # Get all brands id and brand name to populate brands HTML select 1
    $q1=mysqli_query($conect,"SELECT id, brand FROM brands ORDER BY brand ASC");
    $brand_select="";
    while($brand=mysqli_fetch_assoc($q1)){
      $brand_select=$brand_select.'<option value="'. $brand['id'] .'">'. $brand['brand'] .'</option>';
    }
    # Get all models id and model name to populate models HTML select based on the brands ID from html select 1
    $q2=mysqli_query($conect,"SELECT id, brand_id, model FROM models ORDER BY model ASC");
    $models_select="";
    while($model=mysqli_fetch_assoc($q2)){
      $models_select=$models_select.'<option value="'. $model['id'] .'">'. $model['modelo'] .'</option>';
    }
    ?>

    <select name="brand" id="brands" class="s1" onchange="populate(this.id,'modelos')">
      <option value="">Select Brand</option>
      <?= $brand_select ?>
    </select>
    <br>
    <select name="models" id="models" class="s1">
      <option value="">Select Model</option>
      <?= $models_select ?>
    </select>

The id from the brands table is related to the brand_id on the models table for relational purposes.

The brands HTML select are displaying the brands just perfect as it should and the options as is, are showing the full list of models of all brands.

I'm sure that an onChange event should be used on the first HTML select, that is as far as I can get without Javascript.

Of course I've looked other Similar Questions but can't find one that matches my idea about this.

Any suggestion from You the real genius :-)

2
  • 1
    You don't need a json or xml file. Just put both arrays (brands and models) in a javascript array and then update the second select with that values based on the selction of the first (that's your populate() function) Commented Nov 7, 2018 at 22:08
  • Woho, nice suggestion, now since I'm a teflon brain and can't seem to get to grasp javascript (for years now), can you give me an example? Commented Nov 7, 2018 at 22:15

2 Answers 2

1

Here is one way of doing it. PHP is used to produce an array of model options sorted by brand - this makes things easier for the JavaScript. An event listener is added to the brands select which updates the models select appropriately.

PHP

$q1=mysqli_query($conect,"SELECT id, brand FROM brands ORDER BY brand ASC");
$brand_select="";
while($brand=mysqli_fetch_assoc($q1)){
    $brand_select=$brand_select.'<option value="'. $brand['id'] .'">'. $brand['brand'] .'</option>';
}
# Get all models id and model name to populate models HTML select based on the brands ID from html select 1
$q2=mysqli_query($conect,"SELECT id, brand_id, model FROM models ORDER BY brand_id, model ASC");
$models_select="";
while($model=mysqli_fetch_assoc($q2)){
    $models_select[$model['brand_id']][] = '<option value="'. $model['id'] .'">'. $model['model'] .'</option>';
}
echo "<script type=\"text/javascript\">\nvar models = {};\n";
foreach ($models_select as $b => $m) {
    echo "models['$b'] = '" . implode('', $m) . "';\n";
}
echo '</script>';

Javascript

window.addEventListener('load', function () {
    document.getElementById('brands').addEventListener('change', function () {
        if (this.value != '') {
            document.getElementById('models').innerHTML = '<option value="">Select Model</option>' + models[this.value];
        }
    });
});

HTML

<select name="brand" id="brands" class="s1">
  <option value="">Select Brand</option>
  <?= $brand_select ?>
</select>
<br>
<select name="models" id="models" class="s1">
  <option value="">Select Model</option>
</select>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank You Nick perfect solution, it worked like a charm. Jeff proposition is one that I'll look into allso, You guys are geniuses.
@SamuelRamzan no problem. You definitely could use json_encode as @Jeff suggested; I didn't because I already had a similar piece of code to this which didn't use it. I plan to also figure out how I can simplify my code that way.
1

Easy solution is:
Create a php array with all the models that you then write into a javascript array:

$models = [];
while($model=mysqli_fetch_assoc($q2)){
   $models_select=$models_select.'<option value="'. $model['id'] .'">'. $model['modelo'] .'</option>';
   $models[] = $model;
}

?>
<script>
var moduls = <?php echo json_encode($models); ?>  // this makes a JSON string out of the php array, which js can interpret as javascript array/object.
function populateModels(brandId) {
    // TODO:
    // filter the models that have the right brandId
    // generate the options of the fitting models
    // write the options to select #models
}
</script>

A better (because you don't have massive data lying around that you possibly don't use) solution would be to use ajax, as you can find in many questions/answers for "Dynamic selects"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.