Subodh Bisht
Subodh Bisht

Reputation: 899

Set default value in dropdown of html

I'm trying to set the default value of dropdown but I'm failing in to do so. Please tell me what is wrong with this code.

<span>Section Name:</span><select id="editSection" name="classSection" >
<option >A</option><option >B</option><option >C</option><option >D</option>
</select><br>

And here is my javascript code:

$('input[id=editSection]').val($.trim(sec));

im trying to set sec as default value of dropdown. sec is a variable which is got after number of operations and whose value will be A,B,C,D.

Upvotes: 0

Views: 2436

Answers (5)

Neha
Neha

Reputation: 190

<span>Section Name:</span>

<select id="editSection" name="classSection" >
    <option >A</option>
    <option >B</option>
    <option >C</option>
    <option >D</option>
</select><br>


var sec = "C";
$('#editSection option').each(function() {
    if ($(this).text() == sec){
        alert($(this).val());
        $(this).attr('selected', 'selected');
    }
});

Upvotes: 0

SzGyD
SzGyD

Reputation: 88

I found a good explanation on Set the default value in dropdownlist using jQuery. It suggest use:

//for example let your sec variable be "C".
var sec = "C";
// it does the trick, and set default to sec's value.
$("select option:contains("+ $.trim( sec ) + ")").prop('selected',true);

Upvotes: 0

Tomas Santos
Tomas Santos

Reputation: 550

Try just using the id. A select and input are not consider the same type of element.

Fiddle Demo

$('#editSection').val($.trim(sec));

Upvotes: 1

Saranya Sadhasivam
Saranya Sadhasivam

Reputation: 1294

Try the below javascript code

var theText="B";

$("#editSection option").each(function() {
  if($(this).text() == theText) {
    $(this).attr('selected', 'selected');            
  }                        
});

Option text is same as theText variable, the option will be selected.

Upvotes: 0

user2119324
user2119324

Reputation: 597

 $("#editSection").empty().append("<option value='0'>--Select--</option>").append($.trim(sec));

Upvotes: 0

Related Questions