Include select value first in option "select."

Select first I want the value to come. how can I do it?

                $.each(data.departmentList, function (key, value) {
                    $('#searchDepartmentName')
                        .append($("<option></option>")
                            .attr("value", value.mudurlukId)
                            .text(value.mudurlukAdi));
                });
               
                $('#searchDepartmentName').append(optionData);
            },  ```

2 answers

  • answered 2021-01-11 05:43 D. Seah

    you can set the selected attribute accordingly.

    const data = {
      departmentList: [
        {mudurlukId: "1", mudurlukAdi: "test1"},
        {mudurlukId: "2", mudurlukAdi: "test2"}
      ]
    };
    
    $('#searchDepartmentName').html(data.departmentList.map((v, i) => {
        const selected = i === 0 ? " selected" : "";
      return `<option ${selected} value=${v.mudurlukId}>${v.mudurlukAdi}</option>`;
    }));
    <head>
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script>
    </head>
    <body>
    <select id="searchDepartmentName">
    </select>
    </body>

  • answered 2021-01-11 05:46 cmaresh

    This will set the first option to be selected:

    $.each(data.departmentList, function (key, value) {
      const select = $('#searchDepartmentName');
      const elem = $("<option></option>")
        .attr("value", value.mudurlukId)
        .text(value.mudurlukAdi);
      
      select.append(elem)
      
      if (elem.is(":first-child")) {
        select.val(value.mudurlukId);
      }
    });