javascript - Dropdown automatically selected a value -
i need problem. want make dynamically dropdown , when select value 1 dropdown "a", dropdown set "b".
i have javascript function dynamically dropdown this.
<script type="text/javascript"> function coba(){ document.getelementbyid("add").innerhtml += " <inputclass='department_name' type='text' size='50' />"; } </script>
reference: how dynamically change item of 2 related combobox
in short:
- in
file1.php
, retrieve mysqltbl1
, display in combo box a. - on change of combo box a, fetch value of option , pass php file
file2.php
via ajax , display output infile1.php
producedfile2.php
. - in
file2.php
, retrieve mysqltbl2
id passed ajax , generate combo box b.
example:
index.php
<script type="text/javascript"> function getxmlhttpobject() { if (window.xmlhttprequest) { return new xmlhttprequest(); } if (window.activexobject) { return new activexobject("microsoft.xmlhttp"); } return null; } function ajax_function(url, postdata, id) { xmlhttp=getxmlhttpobject(); xmlhttp.open("post", url, true); xmlhttp.setrequestheader("content-type", "application/x-www-form-urlencoded"); xmlhttp.setrequestheader("content-length", postdata.length); xmlhttp.setrequestheader("connection", "close"); xmlhttp.onreadystatechange=function() { if(xmlhttp.readystate==4) { document.getelementbyid(id).innerhtml=xmlhttp.responsetext; } } xmlhttp.send(postdata); } function dispsecond(id) { var params = 'id=' + id ; var divid = 'dispdiv'; ajax_function('ajax_display.php', params, divid); } </script> <?php /* mysqli query retrieve , store in $arraylist(id=>text) example: $arraylist = array(1=>'ford',2=>'chevy'); */ ?> <select id="drop_first" name="drop_first" onchange="return dispsecond(this.value);"> <option value="0">[select]</option> <?php foreach ($arraylist $k=>$v) { echo '<option value="'.$k.'">'.$v.'</option>'; } ?> </select> <div id="dispdiv"></div>
ajax_display.php
<?php $id = isset($_request['id']) ? $_request['id'] : ''; if ($id) { /* mysqli query retrieve , store in $subarray $id example: if $id=1 $subarray = array(1=>'focus',2=>'explorer'); if $id=2 $subarray = array(1=>'cavalier',2=>'impala', 3=>'malibu'); */ ?> <select id="drop_second" name="drop_second"> <option value="0">[select]</option> <?php foreach ($subarray $k=>$v) { echo '<option value="'.$k.'">'.$v.'</option>'; } ?> </select> <?php } ?>
note:
use mysqli or pdo instead mysql
below demo , download based on arrays, can implement using mysqli retrieval.
also can try using $.ajax more easy also.
Comments
Post a Comment