How can I extract the text: mytr161 if what is known to me is this text: 8039089332
<tr bgcolor="#dcdcdc" id="mytr161">
<td align="right" bgcolor="#BDB9B4"><input type="checkbox" id="ck161" name="ck161" value="1" onclick="javascript:changebgcolor('161');"></td>
<td align="center" nowrap=""><small><font size="2">
<a href="MfSchOpen850PODetail.asp?lpo=8039089332&litem=hidingit&Plant=hidingitaswell&lsimplifyordertype=hidden" target="Podetail">8039089332</a>
</font></small> </td>
I have a list of numbers like the text: 8039089332. I want to click the checkmark next to it. To do that I am thinking how to write a javascript code to loop through the list of numbers, and click checkmark, I think, firstly need to find the id of the text: 8039089332. And then probably find a way to trim the id by removing the text 'mytr' and replacing it by 'ck'. This is my first attempt at javascript, I have no idea what to do at this point because I am unable to extract the id for the list of numbers that I have.
Since you're not clicking the checkbox, but want to programmatically "click" them based on the link text
function checkTheBox(searchText) {
// find an <a> tag that has the text to find
var xpath = "//a[text() = '" + searchText + "']";
var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (matchingElement) {
// get the <tr> and trim the "mytr" off of it's id
trID = matchingElement.closest('tr').id.replace(/mytr/,'');
// now mark the box checked for that "ck" id
document.getElementById('ck'+trID).checked = true;
}
}
Then, if you want to loop over every a tag, find the text, find the ID...
for (const a of document.querySelectorAll("a")) {
checkTheBox(a.innerHTML);
}
May want to adjust the for loop instead of document.querySelectAll, maybe target only the table...
Borrowed a lot from https://stackoverflow.com/a/29289196/18392362 plus the "closest('tr')" mentioned above.
Update Since you have a list of numbers you want to find and then check the checkbox:
var myList = [
'8039089332',
'xx42xxxx',
'1123581321'
];
// don't use for (i in ...) adjustment :)
for (var i = 0; i < myList.length; i++) {
checkTheBox(myList[i]);
}