【问题标题】:How can I set the value for an HTML <select>?如何设置 HTML <select> 的值?
【发布时间】:2021-10-17 19:14:29
【问题描述】:

我需要为

我这样做是为了让用户首先看到候选人的服务,然后在出现错误时更改它..

   <span >Service</span>
      <select  class="form-control item pb-2"  name="service" value={{ $candidate->service->service_name }}>
            <option value="Outsourcing"> <span class="font-weight-bold">Outsourcing</span></option>
            <option value="Developpement"> <span class="font-weight-bold">Developpement</span></option>
            <option value="Call center"> <span class="font-weight-bold">Call center</span></option>
        </select>

【问题讨论】:

    标签: html select laravel-8


    【解决方案1】:

    您不能为选择设置默认值。相反,您可以这样做:

    <select  class="form-control item pb-2"  name="service" >
            <option value={{ $candidate->service->service_name }}>{{ $candidate->service->service_name }}</option>
            <option value="Outsourcing"> <span class="font-weight-bold">Outsourcing</span></option>
            <option value="Developpement"> <span class="font-weight-bold">Developpement</span></option>
            <option value="Call center"> <span class="font-weight-bold">Call center</span></option>
    </select>
    

    【讨论】:

    • 谢谢你的回答,我已经试过了,但我两次得到相同的选择,这就是为什么我在寻找其他解决方案,如果没有其他方法,我就用这个
    • 你必须简单地使用 if-else 条件
    【解决方案2】:

    任何选项都可以设置为选中,这将是选择的默认值。这是设置值的标准方法。为什么不使用它?

    选项里面也没有标签

    <select  class="form-control item pb-2"  name="service" >
      <option selected value="{{ $candidate->service->service_name }}">{{ $candidate->service->service_name }}</option>
      <option value="Outsourcing">Outsourcing</option>
      <option value="Development">Development</option>
      <option value="Call center">Call center</option>
    </select>
    

    如果您必须插入一个新选项并选择它,那么您可以使用 JavaScript

    window.addEventListener("load",function() {
      const sel = document.querySelector("[name=service]");
      const val = "{{ $candidate->service->service_name }}";
      const opts = [new Option(val,val),...sel.options]
      sel.length = 0;
      opts.forEach(opt => sel.appendChild(opt));
      sel.value = val;
    })  
    <span>Service</span>
    <select class="form-control item pb-2" name="service">
      <option value="Outsourcing">Outsourcing</span></option>
      <option value="Development">Development</option>
      <option value="Call center">Call center</option>
    </select>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-03
      • 2023-03-09
      • 2020-11-25
      • 2021-11-19
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      相关资源
      最近更新 更多