i want to populate drop down box values on the basis of other drop down box value dynamically(without refreshing the page) using java script. i tried to search on google, but could not find anything. please can anybody help me in this regards.

Thanks

Dani AI

Generated

Useful, modern follow-up to the answers from and : pick one of two simple patterns and harden it for real use.

If the child options are fixed or small, use a client-side map (no server trips) as suggested. If options come from the server, return JSON and fetch it — prefer JSON+fetch over inserting HTML/XML. Example (server returns an array like [{ id: "p1", name: "Product 1" }, ...]):

// assumes <select id="supplier"> and <select id="product">
const sup = document.getElementById('supplier');
const prod = document.getElementById('product');
let currentSignal;

sup.addEventListener('change', async () => {
  prod.innerHTML = '<option>Loading...</option>';
  prod.disabled = true;
  if (currentSignal) currentSignal.abort();
  currentSignal = new AbortController();

  try {
    const res = await fetch('/api/products?supplier=' + encodeURIComponent(sup.value), { signal: currentSignal.signal });
    if (!res.ok) throw new Error('Network');
    const items = await res.json();
    prod.replaceChildren(); // clear
    const frag = document.createDocumentFragment();
    frag.appendChild(new Option('Select product', ''));
    for (const it of items) frag.appendChild(new Option(it.name, it.id));
    prod.appendChild(frag);
    prod.disabled = false;
  } catch (err) {
    if (err.name !== 'AbortError') prod.innerHTML = '<option>Error loading</option>';
  }
});

Practical tips and gotchas:

  • Disable the child select while loading and include a placeholder option.
  • Use AbortController to avoid race conditions if the user changes selection quickly.
  • Cache responses in memory for repeated selections to save requests.
  • For very large lists, page results or switch to an autocomplete/typeahead to avoid huge DOM lists.
  • If supporting old browsers, provide XHR/fetch polyfills and avoid replacement methods not present in legacy engines.

Tiebacks: 's XHR demo proves the idea works; the above shows a cleaner, more robust modern pattern and common production hardening (loading state, aborts, caching, error handling).

Recommended Answers

All 3 Replies

This can be achieved if you prefer using AJAX in your page. To get the basic of it, here's a simple demo for you.
This example comes in 2 separated html document: the main.html which holds the entire script, and the request.html that holds another options and will be injected to the main.html upon request.
Here's the code for the main.html:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title>JavaScript Demo</title>
<script type="text/javascript">
// <![CDATA[
/* No editing required -
   For demonstrational purposes only. */


// Declaring variables
var ajax, update, xmlData, getOptions;
var obj, select, option;

// This is a simple prototype that will skip the long declaration of ( element.getElementsByTagName( tagName )[reference] ).
// And now can be defined as element.obj( tagName, reference )
obj = Object.prototype.obj = function( tn, ref ) {
   if (( tn ) && ( typeof ref === "number" ) && ( ref !== null )) {
   return ( this.getElementsByTagName( tn )[ ref ] );
   } else {
   return (  this.getElementsByTagName( tn ));
   } 
};

// This is the function reference which is the one who handle's and process the request sent by the XMLHttpRequest object.

// And considered as the most important part of the whole program. 
getOptions = function() {
select = xmlData.responseXML.obj("select", 0)
option = select.obj("option");
oLen = option.length;
   for ( x = 0; x < oLen; x++ ) { document.obj("select")["lists"].remove( x );
document.obj("select")["lists"].add( new Option( option[x].childNodes[0].nodeValue,  option[x].getAttribute("value") ), x );
   }
};

ajax = function ( url ) {
xmlData = null;
   if ( window.XMLHttpRequest ) {
   xmlData = new XMLHttpRequest();
   } else if ( window.ActiveXObject ) {
      try {
      xmlData = new ActiveXObject("Microsoft.XMLHTTP");
      } catch( e ) {
          xmlData = new ActiveXObject("Msxml2.XMLHTTP");
      }
   }
   if ( xmlData !== null ) {
   xmlData.onreadystatechange = getOptions; 
   xmlData.open("GET", url, true);
   xmlData.send( null );
   } else {
     alert("\nYour browser does not support AJAX Request!"); 
   }
};

update = function( sel ) {
sel = ( document.getElementById ) ? document.getElementById( sel ) : document.all.sel;

index = sel.selectedIndex;

ajax( sel.options[index].value );
return;
}
// ]]>
</script>
</head>
<body>
<div id="content">
<form id="ajaxForm" action="#" onsubmit="return false;">
<div>
<select id="lists" name="lists" size="1" onchange="update( this.id );">
<option value="">Default List</option>
<option value="">Default List</option>
<option value="">Defaut List</option>
<option value="request.html">AJAX Demo - Request Lists!</option>
</select>
</div>
</form>  
</div>
</body>
</html>

And this goes for the request.html

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Request Page</title>
</head>
<body>
<div id="content">
<form id="frm" action="*" onsubmit="return false;">
<div>
<select id="sel" name="sel" size="1" onchange="ajax.listed(this.id);">
<option value="">Requested List</option>
<option value="">Requested List</option>
<option value="">Requested List</option>
<option value="main.html">AJAX Demo - Default Page!</option>
</select>
</div>
</form>
</div>
</body>
</html>

Hope you find it useful...

Let you have two combo one is for supplier & another one is for products. When user select a supplier then you wants populate product combo. Am i right?

<select name="supplier" onchange="products(this)">
.................................................................................

NOW WRITE THE products METHOD LIKE:

function products(supplier) {
    var prodcombo = supplier.form.elements["productcombo name"];
//remove previous data    
while (prodcombo.options.length) {
        prodcombo.remove(0);
    }
    var choice = supplier.options[supplier.selectedIndex].value;
................................................
// Now you got both combo. So populate.....
}

thank you very much for so helpful scripts.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.