Chud37
Chud37

Reputation: 5007

When appending an <option></option> in jQuery, how to set selected?

In my code, I empty a <select> element and rebuild it again with available times.

However I am trying to set the <option> to selected if it matches the previously selected time:

if(time == currenttime) {
    console.log("Matched Time "+currenttime);
    $("#time-start").append($("<option></option>").attr("value", time).text(time)).prop("selected","selected");
} else {
    $("#time-start").append($("<option></option>").attr("value", time).text(time));
}

I get the console message Matched Time but the .prop("selected","selected") isn't setting the newly created option to be selected.

How can I set it to be selected?

Upvotes: 1

Views: 1006

Answers (3)

Sirko
Sirko

Reputation: 74076

I think your code will get more readable like this (and thus makes it easier to set the selected property at the right place):

let $opt = $("<option></option>").attr("value", time).text(time);
if(time == currenttime) {
    console.log("Matched Time "+currenttime);
    $opt.prop("selected","selected");
}
$("#time-start").append($opt);

Upvotes: 4

Jaimin Dave
Jaimin Dave

Reputation: 1222

Change it to following:

$("#time-start").append($("<option></option>").prop("selected",true).attr("value", time).text(time));

Upvotes: 1

Satpal
Satpal

Reputation: 133403

You were close, set selected with option element

var option = $("<option>", {"selected" : time == currenttime, text: time, value: time });
$("#time-start").append(option );

OR, Use .val()

$("#time-start").val(time)

Upvotes: 1

Related Questions