问题
I am a newbie to javascript, and I would like to use a javascript function to validate data in a text box.
I have 1 textbox (txtScore), 1 label (lblMark) and 1 label (lblValidation). When the score is higher thatn the mark, i want the ScoreValidation function in javascript to fire, and display a message in lblValidation.
My text box is in a gridview. The gridview is in a control and I am working on an asp.net project.
This is the code that I have so far in my control:
<asp:ObjectDataSource ID="DS" runat="server" TypeName="BLL.MAnswer" DataObjectTypeName="DTO.MAnswer"
SelectMethod="Select" InsertMethod="Update" UpdateMethod="Update" DeleteMethod="Update">
<SelectParameters>
<asp:ControlParameter Name="MAppID" ControlID="lblMAppID" Type="Int16" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:GridView ID="GVQuestion" runat="server" SkinID="QuestionGrid" DataSourceID="DS">
<Columns>
<asp:TemplateField ItemStyle-VerticalAlign="Top">
<ItemTemplate>
<asp:Label ID="lblValidation" runat="server" ForeColor="Red" />
<asp:Label ID="lblMark" Text='<%# Eval("Mark") %>' runat="server"/>
<asp:TextBox ID="txtScore" runat="server" Text='<%# Eval("Score") %>' OnChange="ScoreValidation()"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<script type="text/javascript">
function ScoreValidation() {
var Score = document.getElementById('txtScore').value;
var Mark = document.getElementById('lblMark').value;
var Validation = "Score cannot be higher than mark";
if (Score > Mark) document.getElementById('lblValidation').value = "Score cannot be higher than mark";
}
回答1:
This is too late but I thought I should leave a message for future reference for other Googlers.
I agree with Csdtesting's answer and that's the easiest. But, I disagree with him because he said this cannot be done from JavaScript. Here's how you do this in JavaScript. Client side validations can be done using JavaScript because ultimately all server controls rendered into HTML. Even the RangeValidator uses JavaScript to validate. You were in the correct path and just didn't know how to get the ids of each control. That's alright, you'll get there :-)
Here's how you'd do it in vanilla JavaScript. (I'll explain after I've given you the working code)
Your Script should be modified like this. Note that your function now accepts one parameter. (Code is self explanatory and I tried to add comments where possible.)
<script type="text/javascript">
/*
obj - txtScore object
*/
function ScoreValidation(obj) {
// Create all your objects based on the obj object (in this case it's the html object of txtScore text box)
var txtScore = document.getElementById(obj.id);
var lblMark = document.getElementById(obj.id.replace('txtScore', 'lblMark'));
var lblValidation = document.getElementById(obj.id.replace('txtScore', 'lblValidation'));
// Now get the values to compare
var Score = txtScore.value;
var Mark = lblMark.innerHTML; // Labels (ultimately becomes Spans doesn't have a value. therefore you need to use inner HTML)
// You need to convert Mark to int since you cannot compare two data types (I.e. int vs html)
if (Score > parseInt(Mark)) {
lblValidation.innerHTML = "Score cannot be higher than mark";
txtScore.focus(); // Don't leave the text box until user fix the validation issue
}
else {
// reset your validation message label if all is good
lblValidation.innerHTML = "";
}
}
</script>
Then in your markup code instead of just calling the JavaScript function without a parameter pass the current object (I.e. this In JavaScript this represents the current object).
<asp:TextBox ID="txtScore" runat="server" Text='0' onBlur="ScoreValidation(this)"/>
Note that I've used onBlur instead of OnChange event because it serves better to validate. (and, when you write client side events start with simple case rather than capitals. This distinguishes sever side events from client side events. It doesn't matter but it's better :-))
Further Explanation
First of all you must understand that your server side controls will be converted to a html equivalent and each control has an ID (one you define at control creation or design time and the one that used by the Server), UniqueID (Unique ID used by the server) and a ClientID (id that'll be rendered to client side by the server. This is the ID that you need in JavaScript to uniquely identify the element in each row).
Secondly, you must understand that there's an object hierarchy both at server side and client side. So, when the server is deciding the ClientIDs for your controls it take this server side object hierarchy into consideration. And, since your controls are within a GridView it'll also take the row number (starting with 0) into consideration. Then it spits out a unique id.
E.g. The ClientID of the txtScore text box of the first row would be
GVQuestion_txtScore_0
Note that this could be slightly different if your GridView is contained within another object or in a UserControl etc and if you are running your application on multiple servers. So it becomes complex :-)
But, JavaScript takes all your worries away and gives you this. This represents the current client side object.
Hope you understand and learnt something.
All the best in learning JavaScript :-)
回答2:
I suggest to use the RangeValidator control.
<asp:RangeValidator id="Range1"
ControlToValidate="TextBox1"
MinimumValue=""
MaximumValue="<%# Eval("Mark") %>"
Type="Integer"
Text="The value must be integer and greater or equal than mark"
runat="server"/>
来源:https://stackoverflow.com/questions/26049483/validatiing-a-textbox-in-a-gridview-using-javascript-on-onchange-event-not-work