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

4
  • 2
    That's because "not required" does contain "required" Commented Apr 27, 2020 at 8: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. Commented Apr 27, 2020 at 8:46
  • Possible answer: stackoverflow.com/questions/499405/… Commented Apr 27, 2020 at 8:47
  • If you need to find by exact text, then you need to use .filter - see the answer here; stackoverflow.com/a/496126/2181514 Commented Apr 27, 2020 at 8:50

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.