简体   繁体   中英

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?

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.

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 .

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM