I have a javascript to enable text boxes when called, I want to trigger this code when a user picks value "Custom" from a dropdownlist, so that I can display/Hide these new textboxes.
function setVisibility(DropDownListID) {
var element = document.getElementById(DropDownListID);
var element1 = document.getElementById("TestBox1");
if (element.value == "Custom") {
element1.visible = !element1.visible ;
}
<asp:DropDownList ID="DateRangeDropDownList" runat="server" Enabled="True" onChange="setVisibility('DateRangeDropDownList');">
<asp:ListItem>Some Value</asp:ListItem>
<asp:ListItem>Custom</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="TestBox1" runat="server"></asp:TextBox>
For some reason it doesn't seem to work. Any ideas?
Because ASP.NET render's your control's is different than you specify in your function call. Use control's ClientID property to get rendered id attribute for a server side control. Here I put dropdown itself as a parameter, and access to your textbox by it's ClientID :
function setVisibility(yourDropdown) {
var element1 = document.getElementById(<%= TestBox1.ClientID %>);
if (yourDropdown.value == "Custom") {
element1.visible = !element1.visible ;
}
<asp:DropDownList ID="DateRangeDropDownList" runat="server" Enabled="True"
onChange="setVisibility(this);">
<asp:ListItem>Some Value</asp:ListItem>
<asp:ListItem>Custom</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="TestBox1" runat="server"></asp:TextBox>
Related
I have an asp dropdown and I am trying to validate it but the validating is just not working.
My dropdown and validator:
<asp:DropDownList CssClass="form-control"
runat="server" ID="cmb_Addresses"
ValidationGroup="ShippingAddress">
</asp:DropDownList>
<asp:RequiredFieldValidator ControlToValidate="cmb_Addresses"
ValidationGroup="ShippingAddress"
InitialValue="0"
Display="dynamic"
ErrorMessage='Please select an address'
runat="server"/>
And here is the method that populates the dropdown:
private void SetupAddresses()
{
var accountService = new AccountService();
var userService = new UserService();
var username = userService.GetLoggedInUser();
var addresses = accountService.GetAddressesForUser(username);
cmb_Addresses.Items.Clear();
cmb_Addresses.Items.Add(new System.Web.UI.WebControls.ListItem("--Please Select--", "0"));
foreach (var address in addresses)
{
cmb_Addresses.Items.Add(new System.Web.UI.WebControls.ListItem(address.Name, GetAddressValue(address)));
}
}
I have tried all the suggestions I have found on the net but they not working.
Oh, the method is called in a !IsPostback
Did you add the correct ValidationGroup to the button that does the PostBack? Because I tested your snippet and it works.
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="ShippingAddress" />
If you did add it to the button, there is probably a javascript error somewhere on the page that is interfering with the Validator. If there are errors the Validator won't work and the form is posted.
I have a sqldatasourece control and formview control inside the the formview i have a place holder that is not visible. I would like to make the place holder visible if a textbox (inside the the same formview) has a value of "yes".
<asp:TextBox ID="Load_SystemsTextBox" runat="server"
Text='<%# Bind("Load_Systems") %>' />
<asp:PlaceHolder ID="PlaceHolderItem3Yes" runat="server" Visible="False">
the value returned from the database equals yes
</asp:PlaceHolder>
I'm trying to make the placeholder visible in the cobe behind but the following dosent work
PlaceHolder PlaceHolderItem3Yes = (PlaceHolder)Master.FindControl("PlaceHolderItem3Yes");
TextBox Load_SystemsTextBox = (TextBox)FormView2.FindControl("Load_SystemsTextBox");
if (Load_SystemsTextBox.Text == "YES")
{
PlaceHolderItem2Yes.Visible = true;
}
else
{
PlaceHolderItem2Yes.Visible = false;
}
You can not see a PlaceHolder.
The control renders only its child elements; it renders no markup of its own. Read more here: MSDN
I am using a custom validator to validate a textbox content.
Everytime the user leaves this textbox, my client script is called, which is, in my case, a little bit annoying.
I want the validation only to be performed when the user clicks on a button given button (which is already happening).
Is there any way to avoid the validation to be performed on the OnChange event of the TextBox?
My code is here:
function isGroupNameUnique(sender, args) {
var valid = true;
var tokens = $('#hdnGroupNames').val().split(',');
var groupName = $('#<%= txtGroupName.ClientID %>').val();
$.each(tokens, function (i) {
if (groupName == this)
valid = false;
});
args.IsValid = valid;
}
<asp:TextBox ID="txtGroupName" runat="server" />
<asp:Button ID="btnAddGroup" runat="server" Text = "Add" onclick="btnAddGroup_Click" class="bGraySmaller" ValidationGroup="AddGroup"/>
<asp:CustomValidator ID="validatorGroupNameAlreadyExists" runat="server" ControlToValidate="txtGroupName" ErrorMessage="The Group Name has to be unique" ValidationGroup="AddGroup" ClientValidationFunction="isGroupNameUnique" />
Remove the ControlToValidate property on the CustomValidator(what is the only Validator where this property is not mandatory). Set the same ValidationGroup on the TextBox.
<asp:TextBox ID="txtGroupName" ValidationGroup="AddGroup" runat="server" />
<asp:CustomValidator ID="validatorGroupNameAlreadyExists" runat="server" ErrorMessage="The Group Name has to be unique" ValidationGroup="AddGroup" ClientValidationFunction="isGroupNameUnique" />
I've got a CheckBoxList control that I want to require the user to check at least ONE box, it does not matter if they check every single one, or 3, or even just one.
In the spirit of asp.net's validation controls, what can I use to enforce this? I'm also using the Ajax validation extender, so it would be nice if it could look like other controls, and not some cheesy server validate method in the codebehind.
<asp:CheckBoxList RepeatDirection="Horizontal" RepeatLayout="Table" RepeatColumns="3" ID="ckBoxListReasons" runat="server">
<asp:ListItem Text="Preliminary Construction" Value="prelim_construction" />
<asp:ListItem Text="Final Construction" Value="final_construction" />
<asp:ListItem Text="Construction Alteration" Value="construction_alteration" />
<asp:ListItem Text="Remodel" Value="remodel" />
<asp:ListItem Text="Color" Value="color" />
<asp:ListItem Text="Brick" Value="brick" />
<asp:ListItem Text="Exterior Lighting" Value="exterior_lighting" />
<asp:ListItem Text="Deck/Patio/Flatwork" Value="deck_patio_flatwork" />
<asp:ListItem Text="Fence/Screening" Value="fence_screening" />
<asp:ListItem Text="Landscape - Front" Value="landscape_front" />
<asp:ListItem Text="Landscape - Side/Rear" Value="landscape_side_rear" />
<asp:ListItem Text="Other" Value="other" />
</asp:CheckBoxList>
It's easy to do this validation server side, but I am assuming you want to do it client side?
JQuery can do this very easily as long as you have something that all checkbox controls have in common to use as a selector such as class (CssClass on your .NET control). You can make a simple JQuery function and connect it to a ASP.NET custom validator. Remember if you do go the custom validator route to make sure you check it server side as well in case javascript is not working, you don't get a free server side check like the other .NET validators.
For more information on custom validators check out the following links: www.asp.net and
MSDN
You don't need to use JQuery, it just makes the javascript function to iterate and look at all your checkbox controls much easier but you can just use vanilla javascript if you like.
Here is an example I found at: Link to original
<asp:CheckBoxList ID="chkModuleList"runat="server" >
</asp:CheckBoxList>
<asp:CustomValidator runat="server" ID="cvmodulelist"
ClientValidationFunction="ValidateModuleList"
ErrorMessage="Please Select Atleast one Module" ></asp:CustomValidator>
// javascript to add to your aspx page
function ValidateModuleList(source, args)
{
var chkListModules= document.getElementById ('<%= chkModuleList.ClientID %>');
var chkListinputs = chkListModules.getElementsByTagName("input");
for (var i=0;i<chkListinputs .length;i++)
{
if (chkListinputs [i].checked)
{
args.IsValid = true;
return;
}
}
args.IsValid = false;
}
Side Note: JQuery is just a little js file include you need to add to your page. Once you have it included you can use all the JQuery you like. Nothing to install and it will be full supported in the next version of Visual Studio I think.
Here's a cleaner jQuery implementation that allows one ClientValidationFunction for any number of CheckBoxList controls on a page:
function ValidateCheckBoxList(sender, args) {
args.IsValid = false;
$("#" + sender.id).parent().find("table[id$="+sender.ControlId+"]").find(":checkbox").each(function () {
if ($(this).attr("checked")) {
args.IsValid = true;
return;
}
});
}
Here's the markup:
<asp:CheckBoxList runat="server"
Id="cblOptions"
DataTextField="Text"
DataValueField="Id" />
<xx:CustomValidator Display="Dynamic"
runat="server"
ID="cblOptionsValidator"
ControlId="cblOptions"
ClientValidationFunction="ValidateCheckBoxList"
ErrorMessage="One selection required." />
And finally, the custom validator that allows the client function to retrieve the target control by ID:
public class CustomValidator : System.Web.UI.WebControls.CustomValidator
{
public string ControlId { get; set; }
protected override void OnLoad(EventArgs e)
{
if (Enabled)
Page.ClientScript.RegisterExpandoAttribute(ClientID, "ControlId", ControlId);
base.OnLoad(e);
}
}
You can use a CustomValidator for that with a little bit of javascript.
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Select at least one"
ClientValidationFunction="checkCheckBoxList"></asp:CustomValidator>
<script type="text/javascript">
function checkCheckBoxList(oSrc, args) {
var isValid = false;
$("#<%= CheckBoxList1.ClientID %> input[type='checkbox']:checked").each(function (i, obj) {
isValid = true;
});
args.IsValid = isValid;
}
</script>
And for a RadioButtonList
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Select at least one" ClientValidationFunction="checkRadioButtonList"></asp:CustomValidator>
<script type="text/javascript">
function checkRadioButtonList(oSrc, args) {
if ($("input[name='<%= RadioButtonList1.UniqueID %>']:checked").val() == null) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
</script>
Here is another solution that may be considered via Dado.Validators on GitHub.
<asp:CheckBoxList ID="cblCheckBoxList" runat="server">
<asp:ListItem Text="Check Box (empty)" Value="" />
<asp:ListItem Text="Check Box 1" Value="1" />
<asp:ListItem Text="Check Box 2" Value="2" />
<asp:ListItem Text="Check Box 3" Value="3" />
</asp:CheckBoxList>
<Dado:RequiredFieldValidator runat="server" ControlToValidate="cblCheckBoxList" ValidationGroup="vlgSubmit" />
Example codebehind.aspx.cs
btnSubmit.Click += (a, b) =>
{
Page.Validate("vlgSubmit");
if (Page.IsValid) {
// Validation Successful
}
};
https://www.nuget.org/packages/Dado.Validators/
Ref: Check if a checkbox is checked in a group of checkboxes in clientside
We can achieve this by C# also
bool Item_selected = false;
foreach (ListItem item in checkbox.Items)
{
if (item.Selected == true)
{
Item_selected = true;
}
}
if (!Item_selected )
{
//your message to user
// message = "Please select atleast one checkbox";
}
Loop through each of the items in ckBoxListReasons. Each item will be of type 'ListItem'.
The ListItem will have a property called 'Selected' that is a boolean. It's true when that item is selected. Something like:
Dim bolSelectionMade As Boolean = False
For Each item As ListItem in ckBoxListReasons.Items
If item.Selected = True Then
bolSelectionMade = True
End If
Next
bolSelectionMade will be set to true if the user has made at least one selection. You can then use that to set the Valid state of any particular validator control you like.
I have GridView which I can select a row. I then have a button above the grid called Edit which the user can click to popup a window and edit the selected row. So the button will have Javascript code behind it along the lines of
function editRecord()
{
var gridView = document.getElementById("<%= GridView.ClientID %>");
var id = // somehow get the id here ???
window.open("edit.aspx?id=" + id);
}
The question is how do I retrieve the selected records ID in javascript?
I worked it out based on JasonS response. What I did was create a hidden field in the Grid View like this:
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:HiddenField ID="hdID" runat="server" Value='<%# Eval("JobID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="False">
<ItemTemplate>
<asp:LinkButton ID="lnkSelect" runat="server" CommandName="select" Text="Select" />
</ItemTemplate>
</asp:TemplateField>
Then on the OnRowDataBind have code to set the selected row
protected virtual void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Click to highlight row
Control lnkSelect = e.Row.FindControl("lnkSelect");
if (lnkSelect != null)
{
StringBuilder click = new StringBuilder();
click.AppendLine(m_View.Page.ClientScript.GetPostBackClientHyperlink(lnkSelect, String.Empty));
click.AppendLine(String.Format("onGridViewRowSelected('{0}')", e.Row.RowIndex));
e.Row.Attributes.Add("onclick", click.ToString());
}
}
}
And then in the Javascript I have code like this
<script type="text/javascript">
var selectedRowIndex = null;
function onGridViewRowSelected(rowIndex)
{
selectedRowIndex = rowIndex;
}
function editItem()
{
if (selectedRowIndex == null) return;
var gridView = document.getElementById('<%= GridView1.ClientID %>');
var cell = gridView.rows[parseInt(selectedRowIndex)+1].cells[0];
var hidID = cell.childNodes[0];
window.open('JobTypeEdit.aspx?id=' + hidID.value);
}
</script>
Works a treat :-)
1) change your javascript function to use a parameter
function editRecord(clientId)
{ ....
2) output the call in your editRecord button... if you want to avoid dealing with the .net generated ids, just use a simple
<input type="button" onclick="editRecord(your-rows-client-id-goes-here)" />
Based off of your comments to #DaveK's response, in javascript you can set the id of a hidden field to the clientId of the selected row when the user selects it. Then have your editRecord function use the value set on the hidden form field.
one could avoid javascript altogether, by setting anchor tags pre-populated with the query string for each row (although this will effect your table layout, it will need only one click rather than 2 from the user)
insert in the gridview template:
<asp:HyperLink runat="server" ID="editLink" Target="_blank"
NavigateURL='<%# Eval("JobID","edit.aspx?id={0}") %>'>
Edit..
</asp:HyperLink>