简体   繁体   中英

JQUERY Populate “Select” options dynamically based on input from another select element

I would like to change the options in a select element based on what i select in another select element (dropdown box).

I have two select boxes (RUNS and SAMPLES) on my PHP page. What i intend to do is to change options in the second select box based on a query that is performed against a database using the option selected in first select box.

I have a table in my database that connects "SAMPLES" to "RUNS". The first select box is populated by a set of 'RUNS' on page load. I would like the 'SAMPLES' that belong to the selected RUN to populate in the SAMPLES box.

The HTML would be something like

<select name='run_id' id='run_id>
    <option value='1'>RUN 1</option>
    <option value='2'>RUN 2</option>
    <option value='4'>RUN 3</option>
    <option value='5'>RUN 4</option>
</select>

The backend table "sample_runs" has columns run_id and sample_name. I have a PHP script as follows,

<?php
mysql_connect("localhost","uname","pwwd");
mysql_select_db("dbname");
$run_id = $_GET['run_id'];
$sql = "select distinct sample_name from samples where run_id = '$run_id'";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)){
    echo '<option value='.$rs['sample_name'],'>'.$rs['sample_name']."</option>";
}
?>

I can modify the PHP script (easy part), but can someone share some code with me on how to populate the sample name options based on the run_id selected in the RUNS box.

Greatly appreciate the help.

If your data set is small enough, you could send all of the data on page load. Do this by building a JSON object that represents your entire dataset in PHP. You can use PHP's json_encode function to do this: http://php.net/manual/en/function.json-encode.php

Once you've built up a JSON string, you'll need to send it to some JavaScript to handle the population of the sample name options based on the selected run_id. There's a good discussion on that here: How to pass variables and data from PHP to JavaScript?

Finally, you'll need to write JavaScript to do the DOM manipulation necessary to change the contents of the second HTML select box. Here's an example of that: Adding options to select with javascript

If your data set is too large to send in a single request, you'll need to build up a REST API to provide the data for each run when it is selected.

Good luck!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM