Try   HackMD

select下拉式選單的選項option,如何對應後端傳入的資料,在製作CRUD的update頁面時

好用的Blade語法實例03

使用laravel 版本8.x

我在後台發布新的文章時,可以選擇這是哪一種文章,因為我有設文章類型(type)。
我用下拉式選單來做選擇

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

下拉式選單的程式碼,一般長的類似下面這樣。

<select class="form-select" aria-label="Default select example" name="type"> <option selected>文章類型</option> <option value="最新消息">最新消息</option> <option value="寵物保姆">寵物保姆</option> <option value="動保法律">動保法律</option> <option value="一起回家故事">一起回家故事</option> </select>

那問題來了,假設我發了一篇文章,如果我要編輯內文,點擊編輯的時候,進去的編輯頁面,他的文章類型有辦法維持我原本的選擇嗎?如果不能維持,那我編輯內文的時候,還要重新選一次文章的類型,一次還好,每一次都這樣做我會受不了!

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

好啦,是可以解決的喔,我們透過@if``@endif來做判斷,下面是程式碼。

<select class="form-select" aria-label="Default select example" name="type"> <option value="最新消息" @if($news->type == "最新消息") selected @endif>最新消息</option> <option value="寵物保姆" @if($news->type == "寵物保姆") selected @endif>寵物保姆</option> <option value="動保法律" @if($news->type == "動保法律") selected @endif>動保法律</option> <option value="一起回家故事" @if($news->type == "一起回家故事") selected @endif>一起回家故事</option> </select>

@if($news->type == "最新消息") selected @endif,加進去<option value="最新消息">裡,這個$news->type是帶進來的資料,如果資料比較後,符合這個option的value,那就會selected這個option。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

經過比較後,他幫你選好了,終於可以不用擔心了。

tags: laravel laravel.8 blade CRUD Select Html upload 下拉式選單