1

I am trying to set default value in dropdown when HTML page is loaded. I have filled the dropdown values dynamically from code as 0 = Select, 1 = Required and 2 = Not Required

I have written below line of code to set the value as "Required".

$("#ddltest option:contains('Required')").attr('selected', 'selected');

However the "Not Required" option is getting set.

C# fiddler link below: https://dotnetfiddle.net/llbCf3

Hien Nguyen
  • 21,001
  • 7
  • 35
  • 48
BronFe
  • 13
  • 2
  • 2
    That's because "not required" *does* contain "required" – freedomn-m Apr 27 '20 at 08:44
  • 1
    If you know the values, you can use them directly: `$("#ddltest").val(1)`. In the same way that you're checking if `.val() == 0` in the line above. – freedomn-m Apr 27 '20 at 08:46
  • Possible answer: https://stackoverflow.com/questions/499405/change-the-selected-value-of-a-drop-down-list-with-jquery – freedomn-m Apr 27 '20 at 08:47
  • If you need to find by exact text, then you need to use .filter - see the answer here; https://stackoverflow.com/a/496126/2181514 – freedomn-m Apr 27 '20 at 08:50

1 Answers1

2

Your problem is there are 2 text have Required, you can change your jquery code to

$("#ddltest option").filter(function() {
    return $(this).text() == 'Required';
}).prop("selected", true);

Demo at dotnetfiddle https://dotnetfiddle.net/cez5QB

Hien Nguyen
  • 21,001
  • 7
  • 35
  • 48