Hyperjase
Hyperjase

Reputation: 127

JQuery select option Text with JQuery created HTML

I know this has been asked many times here and I've searched for my specific solution but can't figure this out -- before anyone shouts at me, I'm still learning JQuery and know this is NOT how it's done, but this works for me and shows an example of what I'm trying to achieve. I know there's a simpler solution but can't figure out what it is.

My issue is that I'm reading back from a JSON query and need to select a drop down option based off the JSON results. I think my issue is more that the HTML select code is created within JQuery itself. I've experienced such issues previously and .live appeared to solve it, but I'm not sure that's the solution in this instance. Here is the code I currently have - which works but is the wrong method of doing this.

if (calEvent.visitortype == "Customer") {
    Cust = "selected"
    Supp = ""
    Oth = ""
} else if (calEvent.visitortype == "Supplier") {
    Cust = ""
    Supp = "selected"
    Oth = ""                
} else if (calEvent.visitortype == "Other") {
    Cust = ""
    Supp = ""
    Oth = "selected"                
}
$('#msgBox4').html($('#msgBox4').html() + '<div class="table-row"><div class="table-col-l">Visit Type:</div><div class="table-col-r"><select id="type" required="required"><option selected value="" disabled> -- select an option -- </option><option '+Cust+'>Customer</option><option '+Supp+'>Supplier</option><option '+Oth+'>Other</option></select></div></div>')

Upvotes: 0

Views: 31

Answers (1)

Ahs N
Ahs N

Reputation: 8366

This is what I came up with:

$("#type > option:contains('"+calEvent.visitortype+"')").attr("selected", "selected");

Please note that I removed the selected tag from the drop-down that you generate.

See JSFiddle demo here

Change the the first line of the jsfiddle to simulate the type of visit.

Upvotes: 1

Related Questions