1

I'm having the select field as below.

<select id="mySelect1">
  <option value="-1">select</option>
  <option value="1">Node-Red</option>
  <option value="2">Node</option>
  <option value="2">Node-JS</option>
</select>

Note: I have the same value for two options.

When I tried below link suggestion it always set the final matching value.

jQuery: Setting select list 'selected' based on text, failing strangely

example: if I tried to set the value for the drop down as "Node" using the below code, it always selects Node-JS in the drop-down.

$("#mySelect1 option:contains("Node")").attr("selected", true);

So is it possible to set the drop down values using the text(not with matching value ) with the same value for many options ?

Any Suggestions ?

2
  • Why not set the option values unique and then during processing figure out if they're one and the same? Commented Sep 7, 2018 at 15:12
  • Both "Node" and "Node-JS" contain "Node" as part of the value. It's going to select both, try to select both of them, which will result in the last one being selected. Commented Sep 7, 2018 at 15:12

1 Answer 1

0

The option:contains("Node") selector will select all the option that contains the word Node, there's no selector for the exact same text you need to filter the options in this case :

$("#mySelect1 option").filter(function() {
  return $(this).text() === 'Node';
}).attr('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="mySelect1">
  <option value="-1">select</option>
  <option value="1">Node-Red</option>
  <option value="2">Node</option>
  <option value="2">Node-JS</option>
</select>

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

1 Comment

This is almost a straight dup answer from the dup post. Except this uses attr() vs prop()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.