简体   繁体   中英

how do i make the option selected in append jquery in foreach

How can I make the option selected according to the value I get from value[0] in the loop?

$.each(data, function(key, value) {
  $("#cektubuh").append(               
    `<tr>
      <td> 
        <select name="duration_type[]" class="form-control" required>
          // here I want to add the selected option according to $ {value [0]}
          <option value="Semester">Semester</option>
          <option value="Month">Month</option>
        </select>
      </td>
    </tr>`
  });
});

As you have not provided an example of the data , there is no way to know what values are being used here or how they compare. Here is a basic example based on what you have provided.

$.each(data, function(k, v) {
  var row = $("<tr>").appendTo($("#cektubuh"));
  var cell = $("<td>").appendTo(row);
  var sel = $("<select>", {
    name: "duration_type[]",
    class: "form-control"
  }).prop("required", true).appendTo(cell);
  $("<option>", {
    value: v[0]
  }).html(v[0]).prop("selected", true).appendTo(sel);
  $("<option>", {
    value: "Semester"
  }).html("Semester").appendTo(sel);
  $("<option>", {
    value: "Month"
  }).html("Month").appendTo(sel);
});

If it's more complex or has multiple elements, please provide an example of the structure so that a more complete answer can be shown.

if you have value which belongs to options list and you want to show as selected option just do this.

var value = 'some value';
$('name="duration_type[]"').val(value);

it will show that value as selected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM