Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Fill a Text Field from a Drop-Down Box

Status
Not open for further replies.

giza

Technical User
Mar 2, 2010
5
ZA
Hi All,

Being a newbie I've found all the threads on this forum about this topic extremely useful. So, i've cobbled together the attached javascript/html/php/mysql code that uses a first selection box to populate a second selection box that, in turn, populates a text box. i.e. the user selects either bead or utensil that populates the second selection box with the relevant items (either beads or utensils). I link to a database. When the user selects an item in the second drop-down box, a price appears in the text field.

My problem is that I can only seem to get the prices for the first selection, i.e. beads. When I select utensils from the drop-down box I get the same set of prices (i.e. the bead prices) instead of the utensil prices. I would be very grateful for some help on this! Here is my code:
Code:
<hmtl>
<?php
require_once("/..../...php");
?>

<form name="form1"> 
    <select name="types" onChange="fillItems(0);"> 
        <option value="1">Beads</option> 
        <option value="2">Utensils</option> 
    </select> 
    <select name="items" onChange="fillPrices(0);"></select>
    <input type="text" name="prices" value= " " />

</form> 
 
<script type="text/javascript">

var arItems = new Array() 
arItems = [
<?php 

$query = "SELECT item_type, stock_id, model_name, price FROM stock"; 
$result = mysqli_query($dbc, $query); 
$num_rows = mysqli_num_rows( $result ); 
$i = 1; 
while ($row_result = mysqli_fetch_row($result)) { 
    echo "['".$row_result[0]."', '".$row_result[1]."', '".$row_result[2]."', '".$row_result[3]."']"; 
    if ( $i < $num_rows ) 
        echo ", 
        "; 
    $i++;  
} 
?> 
]


function fillItems(int_Start) {
    var fTypes = document.form1.types;
    var fItems = document.form1.items;
    var a = arItems;
    var b, c, d, intItem, intType, intPrice; 

    if ( int_Start >= 0 ) {
	
        for ( b = 0; b < a.length; b++ ) {
            if ( a[b][1] == int_Start )
                intType = a[b][0];
        }
   
        for ( c = 0; c < fTypes.length; c++ ) {
            if ( fTypes.options[ c ].value == intType )
                fTypes.selectedIndex = c;
        }
    }

    if ( intType == null )
        intType = fTypes.options[ fTypes.selectedIndex ].value;

    fItems.options.length = 0;

    for ( d = 0; d < a.length; d++ ) {
        if ( a[d][0] == intType )
            fItems.options[ fItems.options.length ] = new Option( a[d][2], a[d][1] );

        if ( a[d][1] == int_Start )
            fItems.selectedIndex = fItems.options.length - 1; 
        }
    }

function fillPrices() {
    var fItems = document.form1.items;
    var fPrices = document.form1.prices;
    fPrices.length = fItems.options.length;    
    var a = arItems;
    var x = fItems.selectedIndex;

		fPrices = a[x][3];
   		document.form1.prices.value = fPrices;
 
}

</script>

</html>
 
Hi Feherke,

Thanks! Here is the generated HTML code. The names don't make sense I know, just a jumble of test characters at this stage for the "model_name". So basically you have from left to right in each row: item_type, stock_id, model_name, price.
Code:
<hmtl>
Connection to database established

<form name="form1"> 
    <select name="types" onChange="fillItems(0);"> 
        <option value="1">Beads</option> 
        <option value="2">Utensils</option> 
    </select> 
    <select name="items" onChange="fillPrices(0);"></select>
	<input type="text" name="prices" value= " " />
</form> 
 
<script type="text/javascript">

var arItems = new Array() 
arItems = [
['1', '7', 'happy happy', '52.00'], 
        ['1', '8', 'dignbat dong', '23.00'], 
        ['1', '9', 'zongea', '412.00'], 
        ['1', '10', 'asegaai', '474.00'], 
        ['1', '11', 'anckor', '789.00'], 
        ['1', '12', 'zongalero', '12.00'], 
        ['1', '13', '[URL unfurl="true"]wwww',[/URL] '145.00'], 
        ['1', '14', 'ert', '145.00'], 
        ['1', '15', 'werefasdvd', '7895.00'], 
        ['1', '16', 'def', '557.00'], 
        ['1', '21', 'wicker', '147.00'], 
        ['1', '22', 'ertyh', '415.00'], 
        ['1', '23', 'wereerrr', '789.00'], 
        ['1', '24', 'eertt', '789.00'], 
        ['1', '25', 'ser', '789.00'], 
        ['1', '27', 'k5s754', '717.00'], 
        ['1', '28', 'rerv', '1415.00'], 
        ['1', '29', 'cewr', '586.00'], 
        ['1', '30', 'ewqexweqe', '147.00'], 
        ['1', '31', 'dsdsdsadsa', '14.00'], 
        ['1', '32', 'retqret', '417.00'], 
        ['1', '33', 'r23ec21e', '78.00'], 
        ['1', '34', 'rqewrr', '478.00'], 
        ['1', '35', 'wrwrfewfewtg', '417.00'], 
        ['1', '36', 'rewreewrewqr', '145.00'], 
        ['1', '37', 'wqrrewtrtr', '1756.00'], 
        ['1', '38', 'tretergregtrgert', '474.00'], 
        ['1', '39', 'fwrewrer', '4554.00'], 
        ['1', '40', 'rwer', '17.00'], 
        ['1', '41', 'retewttwertre', '744.00'], 
        ['2', '42', 'erewrerewrewrewr', '47458.00'], 
        ['2', '43', 'wrewqrewrqw', '7474.00'], 
        ['2', '44', 'weqtertryterytrwy', '174.00'], 
        ['2', '45', 'terwtretrewt', '747.00'], 
        ['2', '46', 'rerrwttretrwetqew', '444.00'], 
        ['2', '47', 'ewwrtretreyrewy', '445.00'], 
        ['2', '48', 'erewr', '7.00'], 
        ['2', '49', 'as[URL unfurl="true"]www',[/URL] '445.00'], 
        ['2', '50', 'vee', '145.00'], 
        ['2', '51', 'dsaDSAdas', '145.00'], 
        ['2', '52', 'q[URL unfurl="true"]www',[/URL] '78.00'], 
        ['2', '53', 'aassdd', '415.00'], 
        ['2', '54', 'glass bead2', '1455.00'], 
        ['2', '55', 'bowl', '145.00'], 
        ['2', '56', 'saa', '145.00'], 
        ['2', '57', 'sddd', '145.00'], 
        ['2', '58', 'sSEE', '4458.00'], 
        ['2', '59', 'happy happy2', '145.00'], 
        ['2', '60', 'happy happy22432', '145.00'], 
        ['2', '61', '', '345.00'], 
        ['2', '62', 'happy king', '334.00'], 
        ['2', '63', 'dqwddqg', '145.00'], 
        ['2', '64', 'qdasDASCAsa', '145.00'] 
]


function fillItems(int_Start) {
    var fTypes = document.form1.types;
    var fItems = document.form1.items;


    var a = arItems;
    var b, c, d, intItem, intType, intPrice; 

    if ( int_Start >= 0 ) {
	
        for ( b = 0; b < a.length; b++ ) {
            if ( a[b][1] == int_Start )
                intType = a[b][0];
        }
   
        for ( c = 0; c < fTypes.length; c++ ) {
            if ( fTypes.options[ c ].value == intType )
                fTypes.selectedIndex = c;
        }
    }

    if ( intType == null )
        intType = fTypes.options[ fTypes.selectedIndex ].value;

    fItems.options.length = 0;

    
    for ( d = 0; d < a.length; d++ ) {
        if ( a[d][0] == intType )
            fItems.options[ fItems.options.length ] = new Option( a[d][2], a[d][1] );

        if ( a[d][1] == int_Start )
            fItems.selectedIndex = fItems.options.length - 1;
            
    }

    }

function fillPrices() {
    var fItems = document.form1.items;
    var fPrices = document.form1.prices;
	fPrices.length = fItems.options.length;    
    var a = arItems;
    var x = fItems.selectedIndex;

		fPrices = a[x][3];
   		document.form1.prices.value = fPrices;

}

</script>

</html>
 
From what I can gather, you don't seem to be altering your query in any way to reflect the selected choice from your first drop down.

You create a single array every time with the same set of data.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Hi

Phil said:
You create a single array every time with the same set of data.
Yes, but it contains both Beads ( '1' ) and Utensils ( '2' ) items. But indeed it looks very ugly. I suggest to change the structure of the arItems array :
Code:
[b]<hmtl>[/b]

[b]<head>[/b]

[b]<script[/b] [maroon]type[/maroon][teal]=[/teal][green][i]"text/javascript"[/i][/green][b]>[/b]

var arItems = {
  '1':[
    ['7', 'happy happy', '52.00'],
    ['8', 'dignbat dong', '23.00'],
    ['9', 'zongea', '412.00'],
    ['10', 'asegaai', '474.00'],
    ['11', 'anckor', '789.00'],
    ['12', 'zongalero', '12.00'],
    ['13', '[URL unfurl="true"]wwww',[/URL] '145.00'],
    ['14', 'ert', '145.00'],
    ['15', 'werefasdvd', '7895.00'],
    ['16', 'def', '557.00'],
    ['21', 'wicker', '147.00'],
    ['22', 'ertyh', '415.00'],
    ['23', 'wereerrr', '789.00'],
    ['24', 'eertt', '789.00'],
    ['25', 'ser', '789.00'],
    ['27', 'k5s754', '717.00'],
    ['28', 'rerv', '1415.00'],
    ['29', 'cewr', '586.00'],
    ['30', 'ewqexweqe', '147.00'],
    ['31', 'dsdsdsadsa', '14.00'],
    ['32', 'retqret', '417.00'],
    ['33', 'r23ec21e', '78.00'],
    ['34', 'rqewrr', '478.00'],
    ['35', 'wrwrfewfewtg', '417.00'],
    ['36', 'rewreewrewqr', '145.00'],
    ['37', 'wqrrewtrtr', '1756.00'],
    ['38', 'tretergregtrgert', '474.00'],
    ['39', 'fwrewrer', '4554.00'],
    ['40', 'rwer', '17.00'],
    ['41', 'retewttwertre', '744.00'],
  ],
  '2':[
    ['42', 'erewrerewrewrewr', '47458.00'],
    ['43', 'wrewqrewrqw', '7474.00'],
    ['44', 'weqtertryterytrwy', '174.00'],
    ['45', 'terwtretrewt', '747.00'],
    ['46', 'rerrwttretrwetqew', '444.00'],
    ['47', 'ewwrtretreyrewy', '445.00'],
    ['48', 'erewr', '7.00'],
    ['49', 'as[URL unfurl="true"]www',[/URL] '445.00'],
    ['50', 'vee', '145.00'],
    ['51', 'dsaDSAdas', '145.00'],
    ['52', 'q[URL unfurl="true"]www',[/URL] '78.00'],
    ['53', 'aassdd', '415.00'],
    ['54', 'glass bead2', '1455.00'],
    ['55', 'bowl', '145.00'],
    ['56', 'saa', '145.00'],
    ['57', 'sddd', '145.00'],
    ['58', 'sSEE', '4458.00'],
    ['59', 'happy happy2', '145.00'],
    ['60', 'happy happy22432', '145.00'],
    ['61', '', '345.00'],
    ['62', 'happy king', '334.00'],
    ['63', 'dqwddqg', '145.00'],
    ['64', 'qdasDASCAsa', '145.00']
  ]
}

function fillItems(int_Start)
{
  var fTypes=document.form1.types;
  var fItems=document.form1.items;
  var type=fTypes.value;

  fItems.options.length=1;

  if (!type) return;

  for (var i=0,l=arItems[type].length;i<l;i++)
    fItems.options[i+1]=new Option(arItems[type][i][1],arItems[type][i][0]);
}

function fillPrices()
{
  var fTypes=document.form1.types;
  var fItems=document.form1.items;
  var type=fTypes.value;
  var item=fItems.value;

  for (var i=0,l=arItems[type].length;i<l;i++)
    if (arItems[type][i][0]==item)
      document.form1.prices.value=arItems[type][i][2];
}

[b]</script>[/b]

[b]</head>[/b]

[b]<body>[/b]

[b]<form[/b] [maroon]name[/maroon][teal]=[/teal][green][i]"form1"[/i][/green][b]>[/b]
    [b]<select[/b] [maroon]name[/maroon][teal]=[/teal][green][i]"types"[/i][/green] [maroon]onChange[/maroon][teal]=[/teal][green][i]"fillItems(0)"[/i][/green][b]>[/b]
        [b]<option[/b] [maroon]value[/maroon][teal]=[/teal][green][i]""[/i][/green][b]>[/b]- choose type -[b]</option>[/b]
        [b]<option[/b] [maroon]value[/maroon][teal]=[/teal][green][i]"1"[/i][/green][b]>[/b]Beads[b]</option>[/b]
        [b]<option[/b] [maroon]value[/maroon][teal]=[/teal][green][i]"2"[/i][/green][b]>[/b]Utensils[b]</option>[/b]
    [b]</select>[/b]
    [b]<select[/b] [maroon]name[/maroon][teal]=[/teal][green][i]"items"[/i][/green] [maroon]onChange[/maroon][teal]=[/teal][green][i]"fillPrices(0)"[/i][/green][b]>[/b]
        [b]<option[/b] [maroon]value[/maroon][teal]=[/teal][green][i]""[/i][/green][b]>[/b]- choose item -[b]</option>[/b]
    [b]</select>[/b]
    [b]<input[/b] [maroon]type[/maroon][teal]=[/teal][green][i]"text"[/i][/green] [maroon]name[/maroon][teal]=[/teal][green][i]"prices"[/i][/green] [maroon]value[/maroon][teal]=[/teal][green][i]""[/i][/green][b]>[/b]
[b]</form>[/b]

[b]</body>[/b]

[b]</html>[/b]
Try to rewrite the PHP part to generate the JSON as above.

Feherke.
 
Thanks Feherke! I'll look at re-writing the PHP!
 
Thanks very much for the help! I've revised my code and it's working now. Don't know whether it's the most elegant solution but it does the job! I've created two arrays, i.e. arItems1 and arItems2. Here's my code:

Code:
<hmtl>
<?php
require_once("/Applications/XAMPP/xamppfiles/mysqli_connect.php");
?>

<form name="form1"> 
    <select name="types" onMouseDown="fillItems(0), clearPrices();"> 
        <option value="1">Beads</option> 
        <option value="2">Utensils</option> 
    </select> 
    <select name="items" onMouseDown="fillPrices(0);"></select>
	<input type="text" name="prices" value= " " />
</form> 
 
<script type="text/javascript">

var arItems1 = new Array() 
arItems1 = [
<?php 


$query = "SELECT item_type, stock_id, model_name, price FROM stock WHERE (item_type = 1)"; 
$result = mysqli_query($dbc, $query); 
$num_rows = mysqli_num_rows( $result ); 
$i = 1; 
while ($row_result = mysqli_fetch_row($result)) { 
    echo "['".$row_result[0]."', '".$row_result[1]."', '".$row_result[2]."', '".$row_result[3]."']"; 
    if ( $i < $num_rows ) 
        echo ", 
        "; 
    $i++; 
} 
?> 
]

var arItems2 = new Array() 
arItems2 = [
<?php 


$query = "SELECT item_type, stock_id, model_name, price FROM stock WHERE (item_type = 2)"; 
$result = mysqli_query($dbc, $query); 
$num_rows = mysqli_num_rows( $result ); 
$i = 1; 
while ($row_result = mysqli_fetch_row($result)) { 
    echo "['".$row_result[0]."', '".$row_result[1]."', '".$row_result[2]."', '".$row_result[3]."']"; 
    if ( $i < $num_rows ) 
        echo ", 
        "; 
    $i++; 
} 
?> 
]

function fillItems(int_Start) {
    var fTypes = document.form1.types;
    var fItems = document.form1.items;
	var a;
    var b, c, d, intItem, intType, intPrice; 
    
if (fTypes.value == 1) {
    a = arItems1;
}   else a = arItems2;

    if ( int_Start > 0 ) {
	
        for ( b = 0; b < a.length; b++ ) {
            if ( a[b][1] == int_Start )
                intType = a[b][0];
        }
   
        for ( c = 0; c < fTypes.length; c++ ) {
            if ( fTypes.options[ c ].value == intType )
                fTypes.selectedIndex = c;
        }
    }

    if ( intType == null )
        intType = fTypes.options[ fTypes.selectedIndex ].value;

    fItems.options.length = 0;

    
    for ( d = 0; d < a.length; d++ ) {
        if ( a[d][0] == intType )
            fItems.options[ fItems.options.length ] = new Option( a[d][2], a[d][1] );

        if ( a[d][1] == int_Start )
            fItems.selectedIndex = fItems.options.length - 1;  
    	}
    }

function fillPrices() {
	var fTypes = document.form1.types;
    var fItems = document.form1.items;
    var fPrices = document.form1.prices;
	fPrices.length = fItems.options.length; 
	var y;
    var x = fItems.selectedIndex;
    
	if (fTypes.value == 1) {
    y = arItems1;
		}   else y = arItems2;

		fPrices = y[x][3];
   		document.form1.prices.value = fPrices;

}

function clearPrices(){
	   		document.form1.prices.value = null;
}
</script>

</html>
 
Hi

Glad to see you managed to solve it. I am impressed by your multiple array trick. But I have to say, I would prefer to keep all data in a single arItems object.

Let us shorten the data abit for readability. So if we want to generate this JavaScript source code :
JavaScript:
[b]var[/b] arItems [teal]=[/teal] [teal]{[/teal]
  [green][i]'1'[/i][/green][teal]:[[/teal]
    [teal][[/teal][green][i]'7'[/i][/green][teal],[/teal] [green][i]'happy happy'[/i][/green][teal],[/teal] [green][i]'52.00'[/i][/green][teal]],[/teal]
    [teal][[/teal][green][i]'8'[/i][/green][teal],[/teal] [green][i]'dignbat dong'[/i][/green][teal],[/teal] [green][i]'23.00'[/i][/green][teal]][/teal]
  [teal]],[/teal]
  [green][i]'2'[/i][/green][teal]:[[/teal]
    [teal][[/teal][green][i]'42'[/i][/green][teal],[/teal] [green][i]'erewrerewrewrewr'[/i][/green][teal],[/teal] [green][i]'47458.00'[/i][/green][teal]],[/teal]
    [teal][[/teal][green][i]'43'[/i][/green][teal],[/teal] [green][i]'wrewqrewrqw'[/i][/green][teal],[/teal] [green][i]'7474.00'[/i][/green][teal]][/teal]
  [teal]][/teal]
[teal]}[/teal]
The easiest is to build up a similar PHP array like this :
PHP:
[navy]$arItems[/navy][teal]=[/teal][b]array[/b][teal]([/teal]
  [green][i]'1'[/i][/green][teal]=>[/teal][b]array[/b][teal]([/teal]
    [b]array[/b][teal]([/teal][green][i]'7'[/i][/green][teal],[/teal] [green][i]'happy happy'[/i][/green][teal],[/teal] [green][i]'52.00'[/i][/green][teal]),[/teal]
    [b]array[/b][teal]([/teal][green][i]'8'[/i][/green][teal],[/teal] [green][i]'dignbat dong'[/i][/green][teal],[/teal] [green][i]'23.00'[/i][/green][teal])[/teal]
  [teal]),[/teal]
  [green][i]'2'[/i][/green][teal]=>[/teal][b]array[/b][teal]([/teal]
    [b]array[/b][teal]([/teal][green][i]'42'[/i][/green][teal],[/teal] [green][i]'erewrerewrewrewr'[/i][/green][teal],[/teal] [green][i]'47458.00'[/i][/green][teal]),[/teal]
    [b]array[/b][teal]([/teal][green][i]'43'[/i][/green][teal],[/teal] [green][i]'wrewqrewrqw'[/i][/green][teal],[/teal] [green][i]'7474.00'[/i][/green][teal])[/teal]
  [teal])[/teal]
[teal]);[/teal]
Then the [tt]json_encode()[/tt] PHP function will transform it into what we need :
PHP:
[b]echo[/b] [green][i]'var arItems='[/i][/green][teal],[/teal][COLOR=darkgoldenrod]json_encode[/color][teal]([/teal][navy]$arItems[/navy][teal]);[/teal]
Note that if in stock.model_name you have a string like "Newman's Own", your code will fail, because you are not escaping the single quote ( ' ). [tt]json_encode()[/tt] takes care of such things.

And how to build up that $arItems array in PHP ? Simple :
PHP:
[navy]$query[/navy] [teal]=[/teal] [green][i]"SELECT item_type, stock_id, model_name, price FROM stock"[/i][/green][teal];[/teal]
[navy]$result[/navy] [teal]=[/teal] [COLOR=darkgoldenrod]mysqli_query[/color][teal]([/teal][navy]$dbc[/navy][teal],[/teal] [navy]$query[/navy][teal]);[/teal]

[navy]$arItems[/navy][teal]=[/teal][b]array[/b][teal]();[/teal]
[b]while[/b] [teal]([/teal][navy]$row_result[/navy] [teal]=[/teal] [COLOR=darkgoldenrod]mysqli_fetch_row[/color][teal]([/teal][navy]$result[/navy][teal]))[/teal]
    [navy]$arItems[/navy][teal][[/teal][COLOR=darkgoldenrod]array_shift[/color][teal]([/teal][navy]$row_result[/navy][teal])][]=[/teal][navy]$row_result[/navy][teal];[/teal]
Note that if once you will have in stock.item_type other values than 1 and 2, my code will need no modification.

Feherke.
 
Thanks Feherke! That's a very neat solution. I have never used the json_encode function before. That's very useful indeed. I'm going to try it out for sure. Thanks a ton! Much appreciated!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top