Tuesday, August 14, 2007

Ext Combobox example... the very basics

I created a fairly sophisticated Ext application with editable grids and layouts several months ago. I now have a requirement for a new application. I thought I would start anew, resisting the temptation to just copy my old code and start modifying. I wanted to start with a clean slate but I was surprised how difficult it was to get started.

After some frustration with documentation and examples trying to get a simple combobox created, I distilled one of the examples down to the essentials. You should be able to install Ext, copy/paste the code below and you should be good to go. There are just two files you are creating, a HTML and ext_main.js...

HTML:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>my combo</title>
<link rel="stylesheet" type="text/css" href="lib/ext/resources/css/ext-all.css" />

<!-- GC --> <!-- LIBS -->
<script type="text/javascript" src="lib/ext/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="lib/ext/ext-all.js"></script>

<script type="text/javascript" src="ext_main.js"></script>

</head>
<body>
<h1>Simple Combo</h1>

<input type="text" id="local-states" size="20"/>

</body>
</html>

Code in ext_main.js:

/*
* Ext JS Library 1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/

// some data used in the examples
Ext.namespace('Ext.exampledata');

Ext.exampledata.states = [
['AL', 'Alabama'],
['AK', 'Alaska'],
['AZ', 'Arizona'],
['AR', 'Arkansas'],
['CA', 'California'],
['CO', 'Colorado'],
['CN', 'Connecticut'],
['DE', 'Delaware'],
['DC', 'District of Columbia'] ];

var combos = {
init : function(){


// simple array store
var store = new Ext.data.SimpleStore({
fields: ['abbr', 'state'],
data : Ext.exampledata.states
});
var cbsite = new Ext.form.ComboBox({
store: store,
displayField:'state',
typeAhead: true,
mode: 'local',
triggerAction: 'all',
emptyText:'Select a state...',
selectOnFocus:true
});

cbsite.applyTo('local-states');

}};
Ext.onReady(combos.init, combos);


4 comments:

Ranjee said...

thanks a lot Andy.. It really helped me in building my first combo box using extJs...

Kangkam Galih said...

Andy can you help me build combo box that retrieve data from sql ?

thank you

Purwo Martono said...

Andy can you help me build combo box that retrieve data from sql ?

thank you

amackay99@gmail.com said...

Kangkam,
Yes, if you want to have a sql database as your combo source, just change the datastore so that it gets its data from a server using either json or xml.

See this post. Basically, replace

var store = new Ext.data.SimpleStore({
fields: ['abbr', 'state'],
data : Ext.exampledata.states
});

with the datastore in the post.