php - How to Display Option Name in Dropdown using Javascript -
i have 2 dropdowns values populated mysql. second dropdown values depends on first dropdown option.
anyways, code working. using code posting hospital_id php. want display hospital_name text on dropdown well, of able display hospital_id.
please see me code below , suggest me solution:
$query = "select bp_id,bp_name mfb_billing"; $result = $db->query($query); while($row = $result->fetch_assoc()){ $categories[] = array("bp_id" => $row['bp_id'], "val" => $row['bp_name']); } $query = "select bp_id, hospital_id, hospital_name mfb_hospital"; $result = $db->query($query); while($row = $result->fetch_assoc()){ $subcats[$row['bp_id']][] = array("bp_id" => $row['bp_id'], "val" => $row['hospital_id']); } $jsoncats = json_encode($categories); $jsonsubcats = json_encode($subcats);
this script:
<script type='text/javascript'> <?php echo "var categories = $jsoncats; \n"; echo "var subcats = $jsonsubcats; \n"; ?> function loadcategories(){ var select = document.getelementbyid("categoriesselect"); select.onchange = updatesubcats; for(var = 1; < categories.length; i++){ select.options[i] = new option(categories[i].val,categories[i].bp_id); } } function updatesubcats(){ var catselect = this; var catid = this.value; var subcatselect = document.getelementbyid("subcatsselect"); subcatselect.options.length = 0; //delete options if present for(var = 0; < subcats[catid].length; i++){ subcatselect.options[i] = new option(subcats[catid][i].val,subcats[catid][i].hosp); } } </script>
this form:
<body onload='loadcategories()'> <form id="reportvalue" action="testpj2.php" method="post"> <select id='categoriesselect'> <option value="1">select billing provider</option> </select> <select name='hospitalname[]' id='subcatsselect' multiple='multiple'> <option value="all">select billing provider</option> </select> <label for="from">from</label> <input type="text" id="from" name="from"> <label for="to">to</label> <input type="text" id="to" name="to"> <?php //$a = $_request['hospitalname[]']; //echo $a; ?> <input type="submit" name="submit" value="submit"> </form>
html
<select id="someid"></select>
javascript
document.getelementbyid('someid').innerhtml=" <option value='value1'>"+option1+"</option> <option value='value2'>"+option2+"</option> <option value='value3'>"+option3+"</option>";
update:
for dynamic data sql query,
try putting these codes after query execution. replace $row['value'] , $row['option'] respected dynamic values.
echo"<script type='text/javascript'> var str = '' </script>"; while($row = $result->fetch_assoc()) { echo"<script type='text/javascript'> str = str + '<option value='+".$row['value']."+'>'+".$row['option']."+'</option> </script>"; } echo"<script type='text/javascript'> document.getelementbyid('someid').innerhtml = str </script>";