0

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>')

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You know what, and this is the most confusing thing - I'd already tried such a method but it hadn't work, I wonder if I was placing it in the wrong place (above the code and not below it). Works absolutely perfectly, thank you so much!
The order or the code is important because, the code drop-down needs to be created and be available in the page first before JQuery can act on it and change the attributes of the elements you require. And your welcome :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.