Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Either check a checkbox or fill out the textboxes in Gridview with JS. Any ideas how?

Status
Not open for further replies.

Ihechi

Programmer
Dec 18, 2017
4
US
Greetings mate,

New comer here. Please take it easy on my first post :)

I have a gridview with a control ID of Gridview1.

Inside this gridview are three textboxes and a checkbox with Id of grid1Details.

Our requirement is as follows:

if checkbox is unchecked and textboxes are empty => You cannot submit your form

if checkbox is checked and textboxes are empty => You can submit your form

if checkbox is unchecked and textboxes are not empty => You can submit your form

Upon page load, by default checkbox is unchecked and all textboxes are enabled.

//markup:

Code:
<td> <asp:Button ID="btnNext" CssClass="btnNext" runat="server" Text="Review Form" OnClientClick="BtnClick();javascript:return ValidateTextBox();" OnClick="btnNext_Click" /></td>

   <table>
    <tr>
        <td>
          <asp:gridview ID="Gridview1" gridlines="None" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowDeleting="Gridview1_RowDeleting">
            <Columns>
            <asp:BoundField DataField="RowNumber" Visible="false" HeaderText="Row Number" />
            <asp:TemplateField HeaderText="Name">
             <headerstyle horizontalalign="Left" />
                <ItemTemplate>
                    <asp:TextBox ID="txtsourcename" CssClass="textClass" placeholder="Name...(e.g, Jane Doe)" runat="server" style="width:250px;" class="form-control"></asp:TextBox><br />
                    <asp:CheckBox ID="grid1Details" ClientIDMode="Static" runat="server" Checked="false" AutoPostBack="true" OnCheckedChanged="Grid1CheckChanged" /><span style="color:#ff0000">*Check this box if N/A</span>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Address">
            <ItemStyle HorizontalAlign="Left"></ItemStyle>
                <ItemTemplate>
                    <asp:TextBox ID="txtsourceaddress" CssClass="textClass" placeholder="Address..." runat="server" style="width:250px;" class="form-control"></asp:TextBox><br /><br />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Income">
            <ItemStyle HorizontalAlign="Left"></ItemStyle>
                <ItemTemplate>
                     <asp:TextBox ID="txtsourceincome" CssClass="textClass" placeholder="Income...(example: 1000)" runat="server" style="width:250px;" class="form-control txtsourceincome numeric"></asp:TextBox><br /><br />
                </ItemTemplate>
                       </asp:TemplateField>
            <asp:TemplateField HeaderText="">
                <ItemTemplate>
                 <asp:Button ID="ButtonAdd" runat="server" Text="Add" 
                        onclick="ButtonAdd_Click" CssClass="grvAddButton" OnClientClick="return ValidateEmptyValue();return validate()" /><br /><br /><br>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="">
                <ItemTemplate>
                 <asp:Button ID="sourceDelete" runat="server" Text="Delete" CommandName="Delete"
                         CssClass="grvDelButton" OnClientClick="return confirm('are you sure?')"  /> <br /><br /><br />
                </ItemTemplate>
            </asp:TemplateField> 
            </Columns>
          </asp:gridview>
        </td>
    </tr>
</table>

//JS:

Code:
    <script type="text/javascript">
 
        function ValidateTextBox() {
            checkbox = document.getElementById("grid1Details");
            var textvalue = $(".textClass").attr('value');
            if (!checkbox.checked &&  textvalue != "") {
                    alert("Either check the box or enter value in all textboxes.");
                    return false;
                }
                return true;
            }
      
    </script>

When I run the code, if I check the checkbox, it works because it allows user to submit form.

If however, I don't check the checkbox but fill out the textboxes, I keep getting the alert message that Either check the box or enter value in all textboxes.

Any ideas how to modify the javascript to work as expected?

Thanks in advance.
 
1. Javascript or in your case jquery acts on the finalized HTML, as such the ASP code is not very useful, and can make things harder to see. I recommend you post the finalized HTML once all the ASP has been processed, for a better look of what the Js is actually working with.


2. This: $(".textClass") will bring back an array of all the elements that have the class "textClass". As such an array will not have a value attribute of its own. You'll need to loop through the array and check the value of each textBox that needs to be filled, or not filled. As it stands textvalue will be undefined, and will therefore always be different to an empty string.

If you are only looking to verify the textbox that is associated with the grid, then you need to be more specific about what textbox you are looking for when you are checking its value.

3. Grid or GridVoew is an ASP invention. In JS and HTMl its quite meaningless. It's mostly just a table.







----------------------------------
Phil AKA Vacunita
----------------------------------
OS-ception: Running Linux on a Virtual Machine in Windows which itself is running in a Virtual Machine on Mac OSx.

Web & Tech
 
Using class actually does the opposite of what you just described.

Because the markup is using gridview control, it gives several elements of the same textfield as you correctly described such as $gridview_0, 02, etc.

However, to work around that, you use class. This way, only the text control with the class attribute gets processed.
 
The opposite of what?

This: $(".textClass") will bring back an array of elements that have the class name "textClass" attached. You have at least 3 elements with that class name assigned. Being an array, it does not in and of itself have a value attribute. So this: $(".textClass").attr('value'); will always return "undefined". The elements within the array may themselves have values however. Their actual names, or IDs are not being used to find them and as such do not affect what $(".textClass") returns.

Again, I suggest you post the final HTML, instead of ASP code so we can see what exactly the Jquery is looking at.









----------------------------------
Phil AKA Vacunita
----------------------------------
OS-ception: Running Linux on a Virtual Machine in Windows which itself is running in a Virtual Machine on Mac OSx.

Web & Tech
 
Ok,
Is this what you want to see?

Code:
 <div>
   <table>
    <tr>
        <td>
          <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...(e.g, Jane Doe)" class="form-control textClass" style="width:250px;" /><br />
                    <input id="grid1Details" type="checkbox" name="Gridview1$ctl02$grid1Details" onclick="javascript:setTimeout(&#39;__doPostBack(\&#39;Gridview1$ctl02$grid1Details\&#39;,\&#39;\&#39;)&#39;, 0)" /><span style="color:#ff0000">*Check this box if N/A</span>
                </td><td align="left">
                    <input name="Gridview1$ctl02$txtsourceaddress" type="text" id="Gridview1_txtsourceaddress_0" placeholder="Address..." class="form-control textClass" style="width:250px;" /><br /><br />
                </td><td align="left">
                     <input name="Gridview1$ctl02$txtsourceincome" type="text" id="Gridview1_txtsourceincome_0" placeholder="Income...(example: 1000)" class="form-control txtsourceincome numeric textClass" style="width:250px;" /><br /><br />
                </td><td>
                 <input type="submit" name="Gridview1$ctl02$ButtonAdd" value="Add" onclick="return ValidateEmptyValue();return ValidateTextBox();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" /><br /><br /><br>
                </td><td>
                 <input type="submit" name="Gridview1$ctl02$sourceDelete" value="Delete" onclick="return ValidateTextBox();WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;Gridview1$ctl02$sourceDelete&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="Gridview1_sourceDelete_0" class="grvDelButton" /> <br /><br /><br />
                </td>
			</tr><tr>
				<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
			</tr>
		</table>
	</div>
        </td>
    </tr>
</table>
 
UPDATE:

I was able to use VB to validate the form. If checkbox is not checked and textboxes are blank, the alert message is displayed.

This is great. However, the form still gets submitted.

How do I prevent the form from submitting when the alert is raised?

Code:
        For Each row As GridViewRow In Gridview1.Rows
            Dim namesource As TextBox = TryCast(row.FindControl("txtsourcename"), TextBox)
            Dim nmesource As String = namesource.Text
            Dim addresssource As TextBox = TryCast(row.FindControl("txtsourceaddress"), TextBox)
            Dim addrsource As String = addresssource.Text
            Dim incomesource As TextBox = TryCast(row.FindControl("txtsourceincome"), TextBox)
            Dim incmsource As String = incomesource.Text
            Dim ckb As CheckBox = TryCast(row.FindControl("grid1Details"), CheckBox)
            Dim checkb As Boolean = ckb.Checked
            If checkb = False AndAlso nmesource = "" AndAlso addrsource = "" AndAlso incmsource = "" Then
                ClientScript.RegisterStartupScript([GetType](), "Confirm", "jAlert('Please checked or put text!');", True)
            Else
                ClientScript.RegisterStartupScript([GetType](), "Confirm", "jAlert('Validate Ok!');", True)
            End If
            ' End Try
        Next

I don't know if I should post this in asp.net section of the forum.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top