I am trying to retrieve the index of html elements in a list using Jquery 3.4+.
The common solution can be found in posts like this one or this one.
I have implemented it and it runs well until the values I am trying to retrieve are none others than regular expressions.
Here’s a fiddle of what I have tried:
//let myVar = $("#myList").find(`option[text='^.*.xlsx'])`)[0].index;
let myVar = $("#myList").find(`option:contains('^.*.xlsx')`)[0].index;
console.log(myVar+"");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select size="1" id="myList">
<option selected style="width:100%;">^.+.(txt|csv|xlsx)</option>
<option style="width:100%;">^.+.(jpg|jpeg|png|svg|bmp)</option>
<option style="width:100%;">^.*.xlsx</option>
<option style="width:100%;">^.*.docx</option>
<option style="width:100%;">^.*.csv</option>
<option style="width:100%;">^.*.pdf</option>
</select>
I’d like to add that I can’t escape characters nor change the value of what I’m looking for.
Is there a way to get it working for any value regardless of it being a standard text, a regular expression or whatever could be injected in the search function?
3
Answers
In the snippet you provide there are few mistake.
$("myList")
need to be$("#myList")
because your select has idid="myList"
.text
attribute withoption[text='^.*.xlsx'])
but you don’t have text attribute in youroption
.escape character so in your js you need
\
for the equivalentin html. Also, I noticed that
contains('')
retuned undefined while doingcontains('^.*\.xlsx')
and you needcontains('^.*\\.xlsx')
.I have created following workaround to get the index of option based on the text in option. See the following example:
Still using the same strategy adopting jQuery to select the element through the
:contains
selector https://api.jquery.com/contains-selector/#contains1But you need to escape the backslash
replacing each one with
\\
Here’s a demo that is simulating the input data fetch grabbing it from a text input value:
It seems you’re trying to find the index of the option element that contains the text ‘.xlsx’ when selected from the dropdown. The issue with your code is that you’re using the
.index()
method directly on the selector, which returns the index of the first matched element.try this:
this will give you selected option Index.