1

I have a dropdown with several in it. I am writing some jQuery to default to the of a logged in user. The problem is when some of my text is too similar.

//this variable gets the branch name of the logged in user
var branchName = $(".logged-in-branch-name").text();
//this makes the dropdown select the correct branch for the logged in user
$("#branchcode option:contains('" + branchName + "')").prop('selected', true);

This is all well and good. Except when text is to similar. Example:

"College 1" "College 1 - Online"

When the variable branchName is "College 1", the dropdown always defaults to "College 1 - Online".

When the variable is "College 1 - Online", it correctly goes to the "College 1 - Online" dropdown.

Any thoughts on how I can filter these correctly?

Thanks in advance.

Lucas Gass
  • 23
  • 3
  • 1
    do you want to match exactly? – Sean T Aug 07 '18 at 15:16
  • You might want to select option by value. not contains. https://stackoverflow.com/questions/314636/how-do-you-select-a-particular-option-in-a-select-element-in-jquery – jmag Aug 07 '18 at 15:18

2 Answers2

1

Rather than have contains, check the absolute text value.

$("#branchcode").find('option').each(function(){
    if ($(this).text() === branchName)
    {
        $(this).prop('selected', true);
    }
});

or even

$("#branchcode").find('option').each(function(){
      $(this).prop('selected', $(this).text() === branchName);
});
Sean T
  • 2,414
  • 2
  • 17
  • 23
0

Swap this line:

$("#branchcode option:contains('" + branchName + "')").prop('selected', true);

For this code:

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

The problem with your code is that :contains when used in your case with "College 1" is matching both "College 1" and "College 1 - Online", and I will assume (since you didn't provided the html) that the select is not multiple so the last matching option ends selected.


Depending your html you might need to handle whitespace before or after the text of the option element, just throw a $.trim in there:

return $.trim($(this).text()) === branchName;
Alvaro Castro
  • 811
  • 1
  • 9
  • 26