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 ?

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
AshokDev
  • 73
  • 9
  • Why not set the option values unique and then during processing figure out if they're one and the same? – mccambridge Sep 07 '18 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. – Taplar Sep 07 '18 at 15:12

1 Answers1

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>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • 1
    This is almost a straight dup answer from the dup post. Except this uses attr() vs prop() – Taplar Sep 07 '18 at 15:18