Issue
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?
Solution
Still using the same strategy adopting jQuery to select the element through the :contains
selector https://api.jquery.com/contains-selector/#contains1
But 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:
function fetchInput(){
return document.getElementById('input').value;
}
function search(){
const searchTerm = fetchInput();
const escaped = searchTerm.replace(/\\/g, '\\\\');
let index = $(`#myList option:contains('${escaped}')`)?.index();
console.log(`index: ${index}`);
}
button{
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Search</h1>
<input id="input" value="^.*\.xlsx">
<button onclick="search();">Search</button>
<hr>
<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>
Answered By - Diego D
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.