使用php预选择选择选项 [英] preselect the select option using php

查看:78
本文介绍了使用php预选择选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要完成创建post的表单.现在,在创建该帖子之后,如果要编辑它,我将在编辑页面中显示一个select选项,如下所示. (我正在使用Laravel)

I've a form to be completed to create a post. Now after creating that post, if I want to edit it, I'm showing a select option in the edit page something like below. (I am using Laravel)

<select name="posts">
@foreach($posts as $post)

  <option value="{{$post->id}}"> {{$post->name }} </option>

@endforeach
</select>

现在,我需要使用当前的post name预先选择填充的选择字段.我在URL中有一个帖子ID,可以知道我在哪个帖子中.如何选择正确的选项,而不必在options字段中重复相同的选项. ?

Now I need to preselect the populated select field with the current post name. I have a post id in the URL which I can get know in which post I am in. How can I select the right option without making a duplicate of the same in the options field. ?

推荐答案

在循环内部使用if-else结构.

if ( post is equal to the current post ) {
     <option selected="selected" value="{{$post->id}}"> {{$post->name }} </option>
} else {
    <option value="{{$post->id}}"> {{$post->name }} </option>
}

条件取决于您,是否要使用帖子ID或帖子名称进行检查. (无论您拥有什么).

The condition depends on you, whether you want to use the post id or the post name to check. (Whatever you have available).

这篇关于使用php预选择选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆