当输入一个值时,如果用户在所有值中输入值,我该如何确保?

时间:2017-12-01 16:19:38

标签: c# jquery asp.net

希望我的主题标题有意义。

我有七个gridview控件,从gridview1的ID开始。

请参阅以下代码:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:TextBox ID="txtspousename" runat="server"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Address">
            <ItemTemplate>
                <asp:TextBox ID="txtspouseaddress" runat="server"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Income">
            <ItemTemplate>
                <asp:TextBox ID="txtspouseincome" runat="server"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="LastName" HeaderText="LastName" Visible="false" />
        <asp:TemplateField HeaderText="">
            <ItemTemplate>
                <asp:Button ID="ButtonAdd2" runat="server" Text="Add"
                            OnClick="ButtonAdd2_Click" CssClass="grvAddButton" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

在上面的示例代码中,有三个表单字段, txtspousename txtspouseaddress txtspouseincome

用户可以单击提交按钮而不在任何字段中输入任何值,这很好,因为并非所有gridview控件都需要值。

但是,如果用户输入值,比如输入txtspousename,则必须要求用户在剩余的两个表单字段中输入值。

如果不这样做,则会引发一个错误,即其余两个表单字段必须具有值。

我在下面使用的jquery脚本没有这样做。

我做错了什么?

提前多多感谢。

以下是以下脚本。

        <script type="text/javascript">
            $(function () {
                //Attach click event to each button in gridview
                $("#GridView1").find("input[type='submit']").click(function (event) {
                    var isValid = true;
                    //Find the selected button tablerow(tr)
                    var tr = $(this).closest("tr");
                    if (tr.length > 0) {
                        //check if txtspousename textbox is empty or not
                        if ($.trim(tr.find("input[type='text']").val()) != '') {
                            //Loop through other textboxes and check if its empty or not
                            tr.find('input[type="text"]').each(function () {
                                if ($.trim($(this).val()) == '') {
                                    isValid = false;
                                }
                            });
                            //If empty then display the message
                            if (isValid == false) {
                                alert("Please enter values on other textboxes as well");
                                event.preventDefault();
                            }
                        }
                    }
                })
            });
        </script>


///View Source:

 <script type="text/javascript">
$(".grvAddButton").click(function(event) {
  var $row = $(this).closest("tr");

  var $textboxes = $row.find("input[type=text]");
  var totalTextboxCount = $textboxes.length;
  var $emptyTextboxes = $textboxes.filter(function() {
    return !this.value;
  });
  var emptyTextboxCount = $emptyTextboxes.length;

  //If there are textboxes filled out, but not all of them...
  if (emptyTextboxCount > 0 && emptyTextboxCount !== totalTextboxCount) {
    alert("Please enter values in all textboxes in the row.");
    event.preventDefault();
  } else {                    //DEMO PURPOSES ONLY
    alert("Success!");        //DEMO PURPOSES ONLY
    event.preventDefault();   //DEMO PURPOSES ONLY
  }
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

</head>
<body>
 <form method="post" action="./disclosures.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="survey_form" class="form a">


    <div class="bs-example">
        <p><span id="lblResult" style="font-weight:bold;font-size:12px;"></span></p> 
     <div style="margin-left:35px;margin-top:0px;">


            <!-- All user textboxes for input here -->
            <span style="font-weight:bold;font-size:18px;color:#000000;">Name, title, and email address of employee filling this form</span><br /><br />
           <table>
            <tr>
                <td>
                <div class="input text">
                <label for="lblEname"><span style="font-weight:bold;font-size:16px;color:#000000;">Employee Name</span><span style="color:#ff0000">*</span></label>
                 <input name="txteName" type="text" id="txteName" placeholder="Employee name..." class="form-control" style="width:200px;" />
                <span id="RequiredFieldValidator2" style="font-weight:bold;visibility:hidden;">*</span><br />
                 </div>
                 </td>
                <td>
                 <div class="input text">
                <label id="lblTitle"><span style="font-weight:bold;font-size:16px;color:#000000;">Your title</span><span style="color:#ff0000">*</span></label>
                <input name="txttitle" type="text" id="txttitle" placeholder="Employee title..." class="form-control" style="width:200px;" />
               <span id="RequiredFieldValidator3" style="font-weight:bold;visibility:hidden;">*</span><br />
               </div> 
               </td>
                <td>
                 <div class="input text">
                 <label id="lblEmail"><span style="font-weight:bold;font-size:16px;color:#000000;">Your email address</span><span style="color:#ff0000">*</span></label>
                <input name="txtemail" type="text" id="txtemail" placeholder="Employee email..." class="form-control" style="width:200px;" />
               <span id="RequiredFieldValidator4" style="font-weight:bold;visibility:hidden;">*</span><br />
                </div>
                </td>
                <td>
                 <div class="input text">
                 <label id="lblEmpID"><span style="font-weight:bold;font-size:16px;color:#000000;">Your employee Id</span><span style="color:#ff0000">*</span></label>
                <input name="txtEmpID" type="text" onchange="javascript:setTimeout(&#39;__doPostBack(\&#39;txtEmpID\&#39;,\&#39;\&#39;)&#39;, 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="txtEmpID" placeholder="Badge ID..." class="form-control numeric" style="width:100px;" />
               <span id="RequiredempidValidator1" style="font-weight:bold;visibility:hidden;">*</span><br />
                </div>
                </td>
                <td>

             </td>
            </tr>
           </table>
            <br /><br />

          <span style="font-weight:bold;font-size:18px;color:#000000;">Name and address of income source greater than $1,000.00 (No comma (,)  or period(.), eg 1000)</span><br /><br />             
          <div>
    <table cellspacing="0" id="Gridview1" style="border-collapse:collapse;">
        <tr>
            <th align="left" scope="col">Name</th><th scope="col">Address</th><th scope="col">Income</th><th scope="col">&nbsp;</th><th scope="col">&nbsp;</th>
        </tr><tr>
            <td>
                    <input name="Gridview1$ctl02$txtsourcename" type="text" id="Gridview1_txtsourcename_0" placeholder="Name..." class="form-control" style="width:250px;" />
                </td><td align="left">
                    <input name="Gridview1$ctl02$txtsourceaddress" type="text" id="Gridview1_txtsourceaddress_0" placeholder="Address..." class="form-control" style="width:250px;" />
                </td><td align="left">

                     <input name="Gridview1$ctl02$txtsourceincome" type="text" id="Gridview1_txtsourceincome_0" placeholder="Income...(example: 1000)" class="form-control txtsourceincome numeric" style="width:250px;" />
                </td><td>
                 <input type="submit" name="Gridview1$ctl02$ButtonAdd" value="Add" onclick="return ValidateEmptyValue();WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;Gridview1$ctl02$ButtonAdd&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="Gridview1_ButtonAdd_0" class="grvAddButton" />
                </td><td></td>
        </tr><tr>
            <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
        </tr>
    </table>
</div>
            <span style="font-weight:bold;font-size:18px;color:#000000;">Name and address of income source of spouse greater than $1,000.00 (No comma (,)  or period(.); Example 1000)</span><br /><br />              
            <div>
    <table cellspacing="0" id="grvspouse" style="border-collapse:collapse;">
        <tr>
            <th align="left" scope="col">Name</th><th scope="col">Address</th><th scope="col">Income</th><th scope="col">&nbsp;</th><th scope="col">&nbsp;</th>
        </tr><tr>
            <td>
                    <input name="grvspouse$ctl02$txtspousename" type="text" id="grvspouse_txtspousename_0" placeholder="Name..." class="form-control" style="width:250px;" />
                </td><td align="left">
                    <input name="grvspouse$ctl02$txtspouseaddress" type="text" id="grvspouse_txtspouseaddress_0" placeholder="Address..." class="form-control" style="width:250px;" />
                </td><td align="left">

                     <input name="grvspouse$ctl02$txtspouseincome" type="text" id="grvspouse_txtspouseincome_0" placeholder="Income...(example: 1000)" class="form-control txtsourceincome numeric" style="width:250px;" />
                </td><td>
                 <input type="submit" name="grvspouse$ctl02$ButtonAdd2" value="Add" onclick="return ValidateSPEmptyValue();WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;grvspouse$ctl02$ButtonAdd2&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="grvspouse_ButtonAdd2_0" class="grvAddButton" />
                </td><td></td>
        </tr><tr>
            <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
        </tr>
    </table>
</div>
             <span style="font-weight:bold;font-size:18px;color:#000000;">Name and address of divident(s) with income greater than $1,000.00 (No comma (,)  or period(.), eg 1000)</span><br /><br />              
            <div>
    <table cellspacing="0" id="grvDiv" style="border-collapse:collapse;">
        <tr>
            <th align="left" scope="col">Name</th><th scope="col">Address</th><th scope="col">Income</th><th scope="col">&nbsp;</th><th scope="col">&nbsp;</th>
        </tr><tr>
            <td>
                    <input name="grvDiv$ctl02$txtdividentname" type="text" id="grvDiv_txtdividentname_0" placeholder="Name..." class="form-control" style="width:250px;" />
                </td><td align="left">
                    <input name="grvDiv$ctl02$txtdividentaddress" type="text" id="grvDiv_txtdividentaddress_0" placeholder="Address..." class="form-control" style="width:250px;" />
                </td><td align="left">

                     <input name="grvDiv$ctl02$txtdividentincome" type="text" id="grvDiv_txtdividentincome_0" placeholder="Income...(example: 1000)" class="form-control txtsourceincome numeric" style="width:250px;" />
                </td><td>
                 <input type="submit" name="grvDiv$ctl02$ButtonAdd3" value="Add" onclick="return ValidateDivEmptyValue();WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;grvDiv$ctl02$ButtonAdd3&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="grvDiv_ButtonAdd3_0" class="grvAddButton" />
                </td><td></td>
        </tr><tr>
            <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
        </tr>
    </table>
</div>
            <span style="font-weight:bold;font-size:18px;color:#000000;">Name and address of Reimbursement(s) with income greater than $,000.00</span><br /><br />              
            <div>
    <table cellspacing="0" id="grvReim" style="border-collapse:collapse;">
        <tr>
            <th align="left" scope="col">Name</th><th scope="col">Address</th><th scope="col">Income</th><th scope="col">&nbsp;</th><th scope="col">&nbsp;</th>
        </tr><tr>
            <td>
                  <input name="grvReim$ctl02$txtReimbursename" type="text" id="grvReim_txtReimbursename_0" placeholder="Name..." class="form-control" style="width:250px;" />
                </td><td align="left">
                    <input name="grvReim$ctl02$txtReimburseaddress" type="text" id="grvReim_txtReimburseaddress_0" placeholder="Address..." class="form-control" style="width:250px;" />
                </td><td align="left">

                  <input name="grvReim$ctl02$txtReimburseincome" type="text" id="grvReim_txtReimburseincome_0" placeholder="Income...(example: 1000)" class="form-control txtsourceincome numeric" style="width:250px;" />
                </td><td>
                 <input type="submit" name="grvReim$ctl02$ButtonAd4" value="Add" onclick="return ValidateReimEmptyValue();WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;grvReim$ctl02$ButtonAd4&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="grvReim_ButtonAd4_0" class="grvAddButton" />
                </td><td></td>
        </tr><tr>
            <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
        </tr>
    </table>
</div>
          <span style="font-weight:bold;font-size:18px;color:#000000;">Honoraria from a single source</span>
                <button type="button" class="btn btn-info" data-toggle="popover" title="Honoraria Definition" data-trigger="focus" data-content="A payment given to a professional person for services for which fees are not legally or traditionally required."><span class="glyphicon glyphicon-question-sign" style="color:#ffffff"></span></button>
            <div>
    <table cellspacing="0" id="grvHon" style="border-collapse:collapse;">
        <tr>
            <th align="left" scope="col">Honoraria</th>
        </tr><tr>
            <td>
                    <input name="grvHon$ctl02$txthonoraria" type="text" id="grvHon_txthonoraria_0" placeholder="Honoraria from a single source..." class="form-control" style="width:800px;" />
                </td>
        </tr><tr>
            <td align="right">&nbsp;</td>
        </tr>
    </table>
</div>
            <span style="font-weight:bold;font-size:18px;color:#000000;">Name and address of Gift(s) with income greater than $500.00</span><br /><br />             
            <div>
    <table cellspacing="0" id="grvGift" style="border-collapse:collapse;">
        <tr>
            <th align="left" scope="col">Name</th><th scope="col">Address</th><th scope="col">Income</th><th scope="col">&nbsp;</th><th scope="col">&nbsp;</th>
        </tr><tr>
            <td>
                    <input name="grvGift$ctl02$txtgiftname" type="text" id="grvGift_txtgiftname_0" placeholder="Name..." class="form-control" style="width:250px;" />
                </td><td align="left">
                    <input name="grvGift$ctl02$txtgiftaddress" type="text" id="grvGift_txtgiftaddress_0" placeholder="Address..." class="form-control" style="width:250px;" />
                </td><td align="left">

                     <input name="grvGift$ctl02$txtgiftincome" type="text" id="grvGift_txtgiftincome_0" placeholder="Income...(example: 500)" class="form-control txtgiftincome numeric" style="width:250px;" />
                </td><td>
                 <input type="submit" name="grvGift$ctl02$ButtonAdd6" value="Add" onclick="return ValidateGiftEmptyValue();WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;grvGift$ctl02$ButtonAdd6&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="grvGift_ButtonAdd6_0" class="grvAddButton" />
                </td><td></td>
        </tr><tr>
            <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
        </tr>
    </table>
</div>
              <span style="font-weight:bold;font-size:18px;color:#000000;">Name and address of Organization(s) with income greater than $1,000.00 (No comma (,)  or period(.), eg 1000)</span><br /><br />            
              <div>
    <table cellspacing="0" id="grvOrg" style="border-collapse:collapse;">
        <tr>
            <th align="left" scope="col">Name</th><th scope="col">Address</th><th scope="col">Income</th><th scope="col">&nbsp;</th><th scope="col">&nbsp;</th>
        </tr><tr>
            <td>
                    <input name="grvOrg$ctl02$txtorgname" type="text" id="grvOrg_txtorgname_0" placeholder="Name..." class="form-control" style="width:250px;" />
                </td><td align="left">
                    <input name="grvOrg$ctl02$txtorgaddress" type="text" id="grvOrg_txtorgaddress_0" placeholder="Address..." class="form-control" style="width:250px;" />
                </td><td align="left">

                 <input name="grvOrg$ctl02$txtorgincome" type="text" id="grvOrg_txtorgincome_0" placeholder="Income...(example: 1000)" class="form-control txtsourceincome numeric" style="width:250px;" />
                </td><td>
                 <input type="submit" name="grvOrg$ctl02$ButtonAdd7" value="Add" onclick="return ValidateOrgEmptyValue();WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;grvOrg$ctl02$ButtonAdd7&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="grvOrg_ButtonAdd7_0" class="grvAddButton" />
                </td><td></td>
        </tr><tr>
            <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
        </tr>
    </table>
</div>
              <span style="font-weight:bold;font-size:18px;color:#000000;">Name and address of Creditors(s) with income greater than $7,500.00 (No comma (,)  or period(.), eg 1000)</span><br /><br />            
            <div>
    <table cellspacing="0" id="grvCred" style="border-collapse:collapse;">
        <tr>
            <th align="left" scope="col">Name</th><th scope="col">Address</th><th scope="col">Income</th><th scope="col">&nbsp;</th><th scope="col">&nbsp;</th>
        </tr><tr>
            <td>
                    <input name="grvCred$ctl02$txtcreditorname" type="text" id="grvCred_txtcreditorname_0" placeholder="Name..." class="form-control" style="width:250px;" />
                </td><td align="left">
                    <input name="grvCred$ctl02$txtcreditoraddress" type="text" id="grvCred_txtcreditoraddress_0" placeholder="Address..." class="form-control" style="width:250px;" />
                </td><td align="left">
                     <input name="grvCred$ctl02$txtcreditorincome" type="text" id="grvCred_txtcreditorincome_0" placeholder="Income...(example: 7500)" class="form-control txtcreditorincome numeric" style="width:250px;" />
                </td><td>
                 <input type="submit" name="grvCred$ctl02$ButtonAdd8" value="Add" onclick="return ValidateCredEmptyValue();WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;grvCred$ctl02$ButtonAdd8&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="grvCred_ButtonAdd8_0" class="grvAddButton" />
                </td><td></td>
        </tr><tr>
            <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
        </tr>
    </table>
</div>

 </div></div>
 <table width="200" border="0" style="margin-left: 450px">
  <tbody>
    <tr>
      <td> </td>
      <td> <input type="submit" name="btnNext" value=" Review Form " onclick="BtnClick();WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;btnNext&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="btnNext" class="btnNext" /></td>
      <td></td>
    </tr>
  </tbody></table>

2 个答案:

答案 0 :(得分:0)

这条线很可能找不到任何东西:

$("#GridView1").find("input[type='submit']")

当像Gridviews这样的ASP控件在页面上呈现时,会为它们分配唯一ID,如cphPlaceholder_ct100_Gridview1。出于这个原因,您的选择器#Gridview1实际上可能找不到任何元素。要强制您使用已分配给他们的ID进行渲染,您可以添加属性<asp:Gridview ... ClientIDMode="Static" ...>

替代方法是通过执行$("#<%= Gridview1.ClientID %>")或仅使用唯一的类来检索生成的客户端ID。

我也相信你可以简单地将jQuery简化为类似的东西,但也许只是个人偏好。

&#13;
&#13;
$(".grvAddButton").click(function(event) {
  var $row = $(this).closest("tr");

  var $textboxes = $row.find("input[type=text]");
  var totalTextboxCount = $textboxes.length;
  var $emptyTextboxes = $textboxes.filter(function() {
    return !this.value;
  });
  var emptyTextboxCount = $emptyTextboxes.length;

  //If there are textboxes filled out, but not all of them...
  if (emptyTextboxCount > 0 && emptyTextboxCount !== totalTextboxCount) {
    alert("Please enter values in all textboxes in the row.");
    event.preventDefault();
  } else {                    //DEMO PURPOSES ONLY
    alert("Success!");        //DEMO PURPOSES ONLY
    event.preventDefault();   //DEMO PURPOSES ONLY
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td><input type="text" /></td>
    <td><input type="text" /></td>
    <td><input type="text" /></td>
    <td><input type="submit" class="grvAddButton" /></td>
  </tr>
  <tr>
    <td><input type="text" /></td>
    <td><input type="text" /></td>
    <td><input type="text" /></td>
    <td><input type="submit" class="grvAddButton" /></td>
  </tr>
</table>
&#13;
&#13;
&#13;

可以找到包含多个表格和红色输入突出显示的更完整示例here

答案 1 :(得分:0)

不确定它是否适用于gridview,但您可以尝试为每个控件使用自定义字段验证器,如下所示:

<asp:CustomValidator ID="validator" runat="server"
        ErrorMessage="Error to display"
        Text="*"
        Display="Dynamic"
        ControlToValidate="txtspousename"
        ValidateEmptyText="False" ClientValidationFunction="validateFields" />

和javascript:

<script type="text/javascript">
    function validateFields(s,args){
        // Evaluate conditions like.
        // Get elements id's like: <%= txtspouseaddress.ClientID %
        args.IsValid = true;
    }
</script>

您也可以在服务器端进行验证(在CustomValidator上使用OnServerValidate)。

希望它有所帮助。 祝你好运!