dotNetNewbie
dotNetNewbie

Reputation: 789

Pre-selecting dropdown values

I have a dropdown for hours on my webpage. The backend is returning the value as an int. eg: "TimeHours":12.

The following code doesn't preset the value to 12. However, if I change the BE value from 12 to "12" it works.

How should I get this to work? I tried changing <option value="1">1 </option> to <option value=1>1 </option> and that didn't work too.

<li class="align" >                
 <select id="TimeHours" name="TimeHours" 
       style="width:60px" data-value="{{this.TimeHours}}">                    
       <option value="1">1 </option>
       <option value="2">2 </option>
       <option value="3">3 </option>
       <option value="4">4 </option>
       <option value="5">5 </option>
       <option value="6">6 </option>
       <option value="7">7 </option>
       <option value="8">8 </option>
       <option value="9">9 </option>
       <option value="10">10 </option>
       <option value="11">11 </option>
       <option value="12">12 </option>                       
  </select></li>

Upvotes: 0

Views: 850

Answers (5)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79850

Use jquery .val function..

$('#TimeHours').val(function () {
    return $(this).data('value')['TimeHours'];
});

Assuming data-value='{"TimeHours": "12"}'

DEMO: http://jsfiddle.net/ts594/

Upvotes: 2

saml
saml

Reputation: 6802

Mark the one you want to be selected as selected this way:

   <option value="2">2 </option>
   <option value="3">3 </option>
   <option value="4">4 </option>
   <option value="5">5 </option>                    
  ...
   <option selected value="12">12 </option>

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

Other than adding selected to the correct <option> tag, there is no way to pre-select an option.

That's why I have this code:

(function() {
    // enable default attribute on <select>
    var sels = document.querySelectorAll("select[data-value]"), l = sels.length, i,
        opts, m, j;
    for( i=l-1; i>=0; i--) {
        opts = sels[i].getElementsByTagName('option'); m = opts.length;
        for( j=0; j<m; j++) {
            if( opts[j].value == sels[i].getAttribute("data-value")) {
                sels[i].selectedIndex = j;
                break;
            }
        }
        sels[i].removeAttribute("data-value");
    }
})();

Upvotes: 0

Deleteman
Deleteman

Reputation: 8700

Have you tried?

data-value="{{praseInt(this.TimeHours)}}

Upvotes: 0

ahren
ahren

Reputation: 16959

$(function(){
  var select = $("#TimeHours");
  select.val(select.attr("data-value"));
});

Using .attr() returns a string, as opposed to .data() which converts the value to type.

Upvotes: 3

Related Questions