user782104
user782104

Reputation: 13555

Display a variable when a select box option is selected

For example, the select box

<select>
  <option selected="" value="">Please Select</option>
  <option value='txt'>Text</option>
  <option value='int'>Numbers</option>
  <option value='bool' >Boolean</option>
</select>

has a string

$messageList=array ( 'txt'=>'text message', 'int'=>'int message',
                     'bool'=>'bool message');

What i would like to achieve is to display correspond message when the optition is select?

Upvotes: 0

Views: 550

Answers (3)

Ethan Brown
Ethan Brown

Reputation: 27292

If you want to do this with jQuery:

$messageList= { 'txt':'text message', 'int':'int message','bool':'bool message' };

$('#choices').change( function() { alert( $messageList[ $(this).val() ] ); } );​

JFiddle here:

http://jsfiddle.net/yCHqy/

Upvotes: 0

David Thomas
David Thomas

Reputation: 253506

Assuming that the array you posted was meant to be a JavaScript object (it seems you were using PHP's associative array notation):

​var sel = document.getElementsByTagName('select')[0],
    $messageList= {
    'txt' : 'text message',
    'int' : 'int message',
    'bool' : 'bool message'
    };

sel.onchange = function(){
    var selected = this.value;
    alert($messageList[selected]);
};​​

JS Fiddle demo.

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79850

I don't know php, but First I think you need to use json_encode to convert php array to a javascript object. http://php.net/manual/en/function.json-encode.php

<?php
   $messageList=array ( 'txt'=>'text message', 'int'=>'int message','bool'=>'bool message');

   echo var msgs = json_encode($messageList);
?>

And then in javascript,

$('select').change (function () { 
    alert(msgs[$(this).val()]);
});

Also you need a class/id for the select. because the above code will triggered when you change the option of any select box in the page.

Upvotes: 4

Related Questions