I have several CheckBoxes on an ASP.NET view. From a Javascript function I need to find the checkbox not by ID nor by NAME but by a value in a data-selection-productid attribute on the checkbox.
The CheckBox follows:
<input type="checkbox" asp-for="@si.IsSelected"
data-selection-productid="@si.ProductID"
data-linenumber="@si.LineNumber"
value="@si.ProductID"
onclick="selectionChanged(this)" />
The selectionChanged function reference above is NOT the function that has a need to find the CheckBox, but rather the following Textbox event needs the CheckBox. The below code is inside a foreach loop generating this line of code and the first set of lines of code for the number of products in the collection. It is for that reason that neither ID nor name will work. They would be duplicated. What is NOT duplicated is the value in the data-selection-productid value within the checkbox.
<input type="number" asp-for="@si.Quantity"
data-productid="@si.ProductID"
data-linenumber="@si.LineNumber"
value="@si.Quantity"
onclick="quantityChanged(this)" />
So, from the quantityChanged function, I need to find the CheckBox whose data-selection-productid value is the same as the data-productid value on the above textbox.
I have tried several variations of the below code but to no avail. I have verified that the productid from the textBox is valid and the same as it was when the page was displayed.
theCheckBox = ("input").find(`[data-selection-productid='${productid}']`);
The javascript terminates when execution reaches the above line of code.
Any help would be greatly appreciated.
The reason your code doesn't work, is because you are trying to invoke JQuery functions on a non-JQuery object (you're missing the $ sign).
However, you can do this very easily in plain Javascript. If the product id is saved to the variable productId
, you can use the following query selector:
document.querySelectorAll(`input[data-selection-productid="${productId}"]`);
This selects all 'input' elements that have an attribute 'data-selection-productid' with value 'valuehere'.
Additionally, if the value of the attribute doesn't matter, you can also select all elements that have the 'data-selection-productid' attribute, regardless of its value:
document.querySelectorAll(`input[data-selection-productid]`);