javascript - Js, output a option dropdown list depending on previous dropdown option choice -


[solved]
see dynamic dropdownlist value database if have simular issue, worked me.

trying output dropdown list, populated depending on previous dropdown.

the problem is,

how make second dropdown list dynamic?

the values need add, in second dropdown box comes database.
results stored in php array ($rs).

old php & html used it, before needed options change depending on previous selection.

<select name="re_id" id="re_id"> <?php foreach ($rs $r) { ?>  <option value="<?php echo $r['r_id'] ?>"> <?php echo $r['name'] ?></option>  <?php } ?> </select> 



js - need old php doing, aswell sort selection first dropdown.

var select_list_data = {  're_id': {       1: {         text: ['option1', 'option2', 'option3', 'option4', 'option5'],         value: ['option1', 'option2', 'option3', 'option4', 'option5']     },      2: {         text: ['option6'],         value: ['option6']     }  }  }; 

and yes, ofc have other js code outputs html form.

this code issue.

basicly,
if "1" value selected in first dropdown, display option1-5 in second dropdown.

the js code needs more dynamic, values 1, 2, x+(there more 1 & 2 in db) aswell second dropdown options text & values inside kind of js foreach.., simular php foreach if possible.

any help, advice or link useful information on subject appreciated, have been unable find useful myself..

my suggestion: use ajax

what described classic problem in web-design. 1 of popular recommendations in case use xhr, or - in other words - perform ajax request. useful if intend make new database query when select value changes, , populate additional select up-to-date data.

compared prepopulating possible additional select fields, approach will:

  • significantly reduce bandwidth, if have large selection of selects,
  • enables received data up-to-date possible.

just quick outline of i'm thinking about:

html

<select id="first-select">     <option value="1">one</option>     <option value="2">two</option>     <option value="3">three</option> </select>  <select id="second-select">     <option selected disabled>please choose first</option> </select> 

javascript

document.getelementbyid('first-select').addeventlistener('change', function (e) {     var xhr = new xmlhttprequest();     var elem = e.target || e.srcelement;      // dropdowndata.php echo whatever data gets database query, possibly in json     xhr.open('dropdowndata.php?value=' + elem.value, 'get');     xhr.onload = function () {         // populate `select#second-select` using response server (eg.: xhr.responsetext)         // ...     }     xhr.send(); }); 

you can find concrete example @ http://roshanbh.com.np/2007/12/change-dropdown-list-options-values-from-database-with-ajax-and-php.html

if not familiar approach, recommend reading on ajax , json, powerful tools, , need here.


Comments