Dynamically populate the options of a select, from AJAX call, and add conditional the selected option?
Hello,
I have an AJAX call created by changing the value of select element, and I get the response array with data to populate another select element. This itself is working for me now but I'm not convinced/satisfied how do this.
This how I have realize it now:
- if (result.data[i].fsel) {
- jQuery('#'+flID)
- .append(jQuery("<option></option>")
- .attr("value", result.data[i].tlfc)
- .attr("selected", "selected")
- .text(result.data[i].tlfn);
- } else {
- jQuery('#'+flID)
- .append(jQuery("<option></option>")
- .attr("value",result.data[i].tlfc)
- .text(result.data[i].tlfn));
- }
But I was asking myself and trying to it on another way and at once like:
- jQuery('#'+flID)
- .append(jQuery("<option></option>")
- .attr("value", result.data[i].tlfc)
- + if (result.data[i].fsel)
- .attr("selected", "selected") +
- .text(result.data[i].tlfn));
so that I have not an if ... else, but the attribute "selected" conditional.
I've been googling but I couldn't find this specific example, but I have the feeling that such must be possible.
BR.,
Nico