在使用OnChange事件的JavaScript Validatiing一个文本框在GridView(不工作) [英] Validatiing a textbox in a gridview using javascript on OnChange event (not working)

查看:280
本文介绍了在使用OnChange事件的JavaScript Validatiing一个文本框在GridView(不工作)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个新手的JavaScript,我想用一个JavaScript函数在文本框中验证数据。

I am a newbie to javascript, and I would like to use a javascript function to validate data in a text box.

我有1文本框(txtScore),1标签(lblMark)和1标签(lblValidation)。
当比分是腋臭的标志高,我想在JavaScript中ScoreValidation功能开火,并在lblValidation显示一条消息。

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.

我的文本框是一个gridview。在GridView是在控制,我工作的一个asp.net项目。

My text box is in a gridview. The gridview is in a control and I am working on an asp.net project.

这是code,我至今在我的控制:

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";
    }

推荐答案

这是为时已晚,但我想我应该离开的消息对其他的Google日后参考。

This is too late but I thought I should leave a message for future reference for other Googlers.

我同意Csdtesting的答案,这是最简单的。但是,我不同意他,因为他说这不能从JavaScript完成。这里是你如何在JavaScript中做到这一点。客户端验证可以使用JavaScript,因为最终所有的服务器控件呈现为HTML来完成。即使是 RangeValidator控件使用JavaScript来验证。你在正确的路径,只是不知道如何让每个控件的ID。这是正常的,你会到达那里: - )

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 :-)

下面是你如何做到这一点香草的JavaScript。 (我会解释我已经给你的工作code)之后

Here's how you'd do it in vanilla JavaScript. (I'll explain after I've given you the working code)

你的脚本应该修改这个样子。请注意,您的函数现在接受一个参数。 (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>

然后在你的标记code,而不只是调用不带参数的的JavaScript 函数传递当前的对象(即这个的JavaScript 这个重新presents当前对象)。

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)"/>

请注意,我已经使用的onblur 而不是的OnChange 事件,因为它提供更好的验证。 (而且,当你写客户端的事件用简单的情况下,而不是资金开始这区别于客户端事件断绝端事件不要紧,但最好: - ))

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 :-))

新解

首先,你必须了解你的服务器端控件将被转换为一个HTML相当于每个控制有一个 ID (一个你定义在控件创建或设计时而且使用的服务器之一),的UniqueID (用来唯一标识服务器)和客户端ID (ID那会被服务器呈现给客户端,这是你在JavaScript中需要唯一地标识每一行中的元素)的ID。

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).

其次,你必须明白,有两个在服务器端和客户端对象层次。因此,当服务器是决定你的控件的ClientID它采取这种服务器端对象层次考虑。而且,由于你的控制是一个 GridView控件中它会也借此行号(从0开始)考虑在内。然后吐出了一个唯一的ID。

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.

例如。第一行的 txtScore 文本框的客户端ID是

E.g. The ClientID of the txtScore text box of the first row would be

GVQuestion_txtScore_0 

请注意,如果你的GridView是包含在另一个对象,或在用户控件等,如果您运行的多个服务器上的应用程序,这可能会略有不同。因此,它变得复杂: - )

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 :-)

不过,JavaScript的需要所有的烦恼路程,为您提供了这个。这将重新presents当前客户端的对象。

But, JavaScript takes all your worries away and gives you this. This represents the current client side object.

希望您理解并学到了一些东西。

Hope you understand and learnt something.

: - )

这篇关于在使用OnChange事件的JavaScript Validatiing一个文本框在GridView(不工作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆