3

I have a html dropdown list (its pure html). I need to have the value selected based on query results. Like this:

<select name="state" class="formField">
    <option value="">Select a State</option>
    <option value="AK">Alaska</option>
    <option value="AZ">Arizona</option>
    <option value="AR">Arkansas</option>    
    <option value="CA">California</option>  
    <option value="CO">Colorado</option>    
    <option value="CT">Connecticut</option> 
    <option value="DE">Delaware</option>    
    <option value="DC">District Of Columbia</option>
</select>

So if query for a certain user returns State as 'CT', I need the selected value in dropdown to be CT, is there any way to do it other then checking with if statement on every line?

rrk
  • 15,677
  • 4
  • 29
  • 45
Udaan
  • 79
  • 1
  • 1
  • 10
  • Please share your programming language scenario so we can help you to select the item without using if statements. – Felipe Plets Feb 02 '16 at 02:05
  • so I am getting the values from ColdFusion query. selected value AL and so on. – Udaan Feb 02 '16 at 02:10
  • I recommend you to complement your question with this information to increase the change of your question to be answered. How do you create your select? Are you only printing this HTML, or are you iterating database results to create it? – Felipe Plets Feb 02 '16 at 02:16
  • yes, its only html, that's how it is on our customers site. That's the problem, I don't like the idea of adding condition on each line – Udaan Feb 02 '16 at 02:22
  • 1
    You can use javascript / jquery to assign the selected value for the select-option when page loaded instead. http://stackoverflow.com/questions/13343566/set-select-option-selected-by-value – daniel Feb 02 '16 at 02:26

1 Answers1

2

The easier way is that you create a table, or list for yours states and create your select using cfselect tag:

<cfquery name = "GetAllStates" dataSource = "cf_states"> 
    SELECT code, name
    FROM states
</cfquery> 
<cfselect 
    name="state"
    required="Yes"
    message="Select a State"
    selected="User.State"
    query="GetAllStates"
    display="name"
    value="code"> 
    <!--- Add your default option. --->
    <option value="">Select a State</option> 
</cfselect>

More details about cfselect here.

Another option if you are not able to create the ColdFusion table or list is to use jQuery as follows:

<script type="text/javascript">
$("select[name='state'] option[value=" + <cfoutput>#User.State#</cfoutput> + "]").attr('selected','selected');
</script>
Felipe Plets
  • 7,230
  • 3
  • 36
  • 60
  • converted coldfusion query variable to javascript and passed it to val() – Udaan Feb 02 '16 at 03:50
  • 7
    *create your select using cfselect tag* No, better to avoid the poorly implemented, outdated CF wrappers like cfselect (and their many "quirks"). Just use a standard ` – Leigh Feb 02 '16 at 05:11