.Net 5.0 Javascript
In order to disable all elements on my UI when a specific image link, such as MouseClickIconRow1
or MouseClickIconRow2
, is clicked, I encountered a challenge where I couldn't assign the same ID to all elements due to uniqueness required for UI testing purposes.
My attempt to create a loop using getElementsByName
was unsuccessful, and I also tried passing in a unique element ID as shown below. As someone new to Javascript, this task has proven to be quite challenging.
HTML
<img src="@Model.MouseClickIconThumbnailUrl" id="MouseClickIconRow1" name="IconClick" onclick="DisableEnableLinks(this, true)" width="20" height="35" alt="Mouse Click Here Image"></a>
<img src="@Model.MouseClickIconThumbnailUrl" id="MouseClickIconRow2" name="IconClick" onclick="DisableEnableLinks(this, true)" width="20" height="35" alt="Mouse Click Here Image"></a>
Javascript
function DisableEnableLinks(elem ,xHow) {
document.getElementById(elem).onclick
= function () {
objLinks = document.links;
for (i = 0; i < objLinks.length; i++) {
objLinks[i].disabled = xHow;
//link with onclick
if (objLinks[i].onclick && xHow) {
objLinks[i].onclick =
new Function("return false;" + objLinks[i].onclick.toString().getFuncBody());
}
//link without onclick
else if (xHow) {
objLinks[i].onclick = function () { return false; }
}
//remove return false with link without onclick
else if
(!xHow && objLinks[i].onclick.toString().indexOf("function(){return false;}") != -1) {
objLinks[i].onclick = null;
}
//remove return false link with onclick
else if (!xHow && objLinks[i].onclick.toString().indexOf("return false;") != -1) {
strClick = objLinks[i].onclick.toString().getFuncBody().replace("return false;", "")
objLinks[i].onclick = new Function(strClick);
}
}
}
}
String.prototype.getFuncBody = function () {
var str = this.toString();
str = str.replace(/[^{]+{/, "");
str = str.substring(0, str.length - 1);
str = str.replace(/\n/gi, "");
if (!str.match(/\(.*\)/gi)) str += ")";
return str;
}