Newbie 123
Newbie 123

Reputation: 264

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>`
  });
});

Upvotes: 0

Views: 310

Answers (2)

Twisty
Twisty

Reputation: 30893

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.

Upvotes: 1

sajid
sajid

Reputation: 113

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.

Upvotes: 0

Related Questions