ASP.NET DataList - JavaScript validation of all text fields
Easy setup: Shopping cart as a list of data.
The header has two buttons: Update quantity and remove selected items
Each DataList has (among other things) a text box with id = "txtQty" that stores the number of items in the shopping cart.
The user should be able to change the values in these text boxes and then click the Update Quantity button in the header to save all the changes in one go.
I have the logic for the actual savings, but now I go back to add more validation. I was hoping to call one JavaScript function from the UpdateQuantities button's OnClientClick event, which then loops through all the DataListItems, finds the txtQty textbox, and checks if it is a valid numeric input.
I find it difficult to figure out how to do this. So far, my only real idea would be to loop over the form elements and find anything with an ID that matches "txtQty" (since ASP.NET automatically overwrites the ID) and then validates that particular element. This doesn't seem like the best solution. Are there any better ideas floating around?
a source to share
I ended up using the LongHorn method to get the results I wanted. Using a custom validator, I used the client side validation feature to call a JS function that validated a single text field on a text change event.
It wasn't my ideal solution, but it was helpful. I also have a server side validation for the entire list before any processing is done just in case.
a source to share
Why not put a validator on your DataGrid to check if the qty is a real number? This would be the easiest one to date.
If this is not a solution, I would like all these txtQty textboxes to have the same css class. Then you can use JQuery to find all elements with that class name and step through them. This is much better than looping through the entire form and checking if the element id contains 'txtQty' in its id.
Another way is to have a hidden field that contains all the IDs of the textboxes you want to check. You would add this hidden field when text fields are added. Then just parse the hidden field in the id array and find only those IDs.
a source to share
The duplicate ID is really not very good. You can try assigning a class to the text box - "validate-quantity" is fine because you can apply multiple classes as validation rules.
<input type="textbox" class="validate-quantity validate-min" />
This way, you can iterate through the form that looks for your validation rules, instead of specifically targeting the text field.
a source to share