I have a list of elements that display in my page, and they all have different IDs, and all have the same attributes (textboxes, labels).
-
Element 0
- Textbox
- Textbox
- Label
-
Element 1
- Textbox
- Textbox
- Label
-
Element 2
- Textbox
- Textbox
- Label
etc.
My goal here is to detect when user write something in a textbox attribute of the element to display an error message. To achieve that I’m adding an onkeydown javascript function to each of the attributes. For example :
MyTextbox.Attributes.Add("onkeydown", "javascript:OnChangeData();");
Here is my javascript function :
<script type="text/javascript">
function OnChangeData() {
var info = document.getElementById('<%= infoControl.ClientID%>');
infoDonneePersonnelle.textContent = "Error !.";
}
</script>
Everything works good except the fact that when I write on an attribute of the first element whose Id is 1, my javascript function is triggered with the element of Id 5 (my last element) and display my error message in my last element and not in the first where I wrote.
For summarizing, I have 6 element displayed with attributes, when I write on a textbox of element 1, my javascript function is called but display the error message in my last element no matter if I wrote in the textbox of the first, second or last element.
How can I tell to my function that when I write on a textbox of my first element with ID 0, it should display the error message in my first element with ID 0, not the last one with ID 5.
>Solution :
Modify the way you call OnChangeData to pass the element reference. OnChangeData(this) passes the reference of the element that triggered the event.
<script type="text/javascript">
function OnChangeData(element) {
var parentElement = element.parentElement;
var infoDonneePersonnelle = parentElement.querySelector('.error-message');
if (infoDonneePersonnelle) {
infoDonneePersonnelle.textContent = "Error!";
}
}
</script>