0

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?

Chud37
  • 4,579
  • 12
  • 55
  • 107
  • 1
    you are chaining `.prop()` to the `.append()` call, `.append()` returns the original chained jQuery object, not the appended element. So you are actually trying to set "selected" on the ` – Patrick Evans Jun 13 '17 at 08:40
  • Append all the options first, then just call `$('#time-start').val(time)` – Rory McCrossan Jun 13 '17 at 08:44

3 Answers3

3

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);
Sirko
  • 69,531
  • 19
  • 142
  • 174
  • That works! Just for so i can learn, how is that different from setting it inline as I did above? – Chud37 Jun 13 '17 at 08:42
  • @Chud37 Have a look at your parenthesis. In your code you set the `selected` property on the `#time-start` element and not on the ` – Sirko Jun 13 '17 at 08:43
1

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)
Satpal
  • 129,808
  • 12
  • 152
  • 166
1

Change it to following:

$("#time-start").append($("<option></option>").prop("selected",true).attr("value", time).text(time));
Jaimin Dave
  • 1,194
  • 8
  • 17