-1
      if ($('#inputRoom option:selected').text() == null || $('#inputRoom option:selected').text() == "")          
       {
         $('#inputRoom option').eq(0).attr('selected', 'selected');
       }

i am trying to know through jquery if the user has already selected an option in my html select element. if there's still none, i would automatically set the selected value to the first option. however, this is not working.

is the way i do it is correct?

NOTE: i am populating my select element with the data i obtain from a database when the select element is loaded through $('#inputRoom').ready(....):

UPDATE: its working fine now... both joy and felix are correct... moreover, i found that the positioning of my knockout code causes some issue too... fixed it.. thanks...

var trueData = JSON.stringify(data).substring(10, (JSON.stringify(data).length - 2));
var rooms = trueData.split(',');
$('#inputRoom').empty();
$.each(rooms, function (index, value) { 
  $('#inputRoom')
    .append('<option value="' + value.substring(1, value.length - 1) + '">' + 
       value.substring(1, value.length - 1) + '</option>'); 
});
raberana
  • 11,739
  • 18
  • 69
  • 95
  • The first option is always automatically selected by the browser, you don't need JavaScript for that. – Felix Kling Jun 03 '12 at 14:03
  • possible duplicate of [To get selected value of a dropdown ( – Felix Kling Jun 03 '12 at 14:04

2 Answers2

1

You can use $.val instead

  if (!$('#inputRoom').val())          
   {
     $('#inputRoom option:first').attr('selected', 'selected');
   }

Note

As @Felix Kling said in comment, If you dont have any empty option then you dont need to do this, the first option will be selected by default.

Prasenjit Kumar Nag
  • 13,391
  • 3
  • 45
  • 57
0
$(function(){    

   if (($("#inputRoom").val()=="") ||($("#inputRoom").val()=="0") )
   {
       $('#inputRoom option').eq(1).attr('selected', 'selected');
   }       
});

Assuming your SELECT element is like this

<select id="inputRoom">
    <option value="0" selected></option>
    <option value="1">1</option>
    <option value="2" >3</option>   
</select>

working sample http://jsfiddle.net/fDJW3/7/

Shyju
  • 214,206
  • 104
  • 411
  • 497