如何设置select选项的默认值

how to set a default value for select option

本文关键字:select 选项 默认值 设置 何设置      更新时间:2023-09-26

<script type="text/javascript">
 function submitForm() {
  var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
window.location.href = window.location.pathname + '?lang=' + thelang;
}
</script>
<?php session_start() ?>
<?php
require("config.php");
if(!isset($_GET['lang'])) {
	$lng = 'en';
}
else {
	$lng = $_GET['lang'];
}
?>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 </head>
 <body>
  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
   <label for="lang">Select Language:</label>
    <select id="lang" name="lang" onchange="submitForm()">
     <option value="en"<?php if( $_GET['lang'] != 'ar'){  echo " selected='"selected'"";} ?> > English</option>
     <option value="ar"<?php if( $_GET['lang'] == 'ar'){  echo " selected='"selected'"";} ?> >Arabic</option>
          
   </select>
     
</form>
<textarea cols="70" rows="5" readonly style="resize:none"><?php echo $trans['topnews']; ?> </textarea>
</body>
</html>

我是用PHP实现翻译的新手。我有一个文本,它从数据库中加载内容。一旦选定的值为英语,文本区域将为英语;一旦选定的数值为阿拉伯语,文本区域内容将为阿拉伯语。一切都很好,但在选择任何语言之前第一次加载页面时,我出现了错误(C:''examplep''htdocs''project''shownews.php中的未定义索引:lang(当我选择一个值时,这个错误不再显示

尝试这个

 <option value="en"<?php if( $lng != 'ar'){  echo " selected='"selected'"";} ?> > English</option>
 <option value="ar"<?php if( $lng == 'ar'){  echo " selected='"selected'"";} ?> >Arabic</option>