HTML的选择框的默认值(select选项)如何根据MySQL传来的值动态选定。

因为自学的HTML+CSS+PHP+MySQL,看PHP的时候非常急,没有认真学,有时间再回去看一遍PHP,所以这个问题一直困扰着我,攒了两周,上网搜了很多资源,百度贴吧,CSDN论坛,百度知道,学长等等,看有JavaScript解决的函数,又去自学了JavaScript,结果发现我还是做不到。耗时非常长,最后还是妥协了,去淘宝花30元买了10多行代码(emmm我也非常可耻这种不思考的行为)。
在此分享给大家:
MySQL字段名:
在这里插入图片描述
PHP代码:

//循环将表列出
	while($row=mysqli_fetch_array($result)){
		
		$s1="";$s2="";$s3="";$s4="";$s5="";$s6="";$s7="";
	   if($row['countrycontinent']=="Africa"){
	   	  $s1='selected="selected"';
	   }
	   if($row['countrycontinent']=="Asia"){
	   	  $s2='selected="selected"';
	   }
	   if($row['countrycontinent']=="Europe"){
	   	  $s3='selected="selected"';
	   }
	   if($row['countrycontinent']=="Africa"){
	   	  $s4='selected="selected"';
	   }
	   if($row['countrycontinent']=="North America"){
	   	  $s5='selected="selected"';
	   }
	   if($row['countrycontinent']=="South America"){
	   	  $s6='selected="selected"';
	   }
	   if($row['countrycontinent']=="Antarctica"){
	   	  $s7='selected="selected"';
	   }
	   echo<<<TR
		<form action="{$_SERVER["PHP_SELF"]}" method="post" name="countryinformation">
		<tr>
			<td><input type="hidden" name="countryid" value="{$row['countryid']}">{$row['countryid']}</td>
			<td><input type="text" name="membercountry" maxlength="13" value="{$row['membercountry']}"></td>
			<td><input type="date" name="jointime" value="{$row['jointime']}"></td>
			<td><select name="countrycontinent" value=""> 
				<option {$s1} value="Africa">Africa</option>
				<option {$s2}  value="Asia">Asia</option>
				<option {$s3}  value="Europe">Europe</option>
				<option {$s4}  value="North America">North America</option>
				<option {$s5}  value="Oceania">Oceania</option>
				<option {$s6}  value="South America">South America</option>
				<option {$s7}  value="Antarctica">Antarctica</option>
			</select></td>
			<td><input type="text" name="countryleader" maxlength="20" value="{$row['countryleader']}"></td>
			<td><input type="number" name="countryarea" maxlength="8" value="{$row['countryarea']}"></td>
			<td><input type="text" name="captial" maxlength="7" value="{$row['captial']}"></td>
			<td><input type="submit" name="alter" value="修改"></td>
			<td><input type="submit" name="delete" value="删除"></td>
		</tr>
		</form>
TR;
	}
	echo '</table>';

效果图:
在这里插入图片描述

我还是希望有大佬给我改一改我那个用JavaScript写的代码
坐等有缘人

//JavaScript设置select 默认值
<script type="text/javascript">
function jsSelectItemByValue(objSelect,objItemText) { 
for (var i=0;i<objSelect.options.length;i++){
	console.log(objItemText);
	if (objSelect.options[i].value==objItemText){ 
		objSelect.options[i].selected=true; 
		break; 
		} 
	}
}; 
jsSelectItemByValue(document.forms["countryinformation"].countrycontinent,${countrycontinent});
</script>;

猜你喜欢

转载自blog.csdn.net/qq_43597899/article/details/88366519