[英]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. 我不了解php,但是首先,我认为您需要使用
json_encode
将php数组转换为javascript对象。 http://php.net/manual/en/function.json-encode.php 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, 然后在javascript中
$('select').change (function () {
alert(msgs[$(this).val()]);
});
Also you need a class/id
for the select. 您还需要选择一个
class/id
。 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): 假设您发布的数组是一个JavaScript对象(似乎您正在使用PHP的关联数组符号):
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]);
};
If you want to do this with jQuery: 如果您想使用jQuery:
$messageList= { 'txt':'text message', 'int':'int message','bool':'bool message' };
$('#choices').change( function() { alert( $messageList[ $(this).val() ] ); } );
JFiddle here: JFiddle在这里:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.