I have an asp.net webform and i want my submit button to be disabled if my asp:TextBox is empty and also no selection has been made for my asp:RadioButton.
Currently i have the following for my field but i dont know how i can join this for the radio buttons
JQuery
$(document).ready(function ()
{
$("#MainContent_btnRemoveUser").prop('disabled', true);
$("#MainContent_btnAddUser").prop('disabled', true);
});
// Disables 'Remove' button unless all fields popluted
$("#MainContent_txtRemoveUser").on("change", function ()
{
if ($('#MainContent_txtUsername').val())
{
$("#MainContent_btnRemoveUser").prop('disabled', false);
}
else
{
$("#MainContent_btnRemoveUser").prop('disabled', true);
}
});
HTML
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="txtRemoveUser" CssClass="col-sm-offset-2 col-sm-3 control-label">Enter Name To Be Removed</asp:Label>
<div class="col-sm-3">
<asp:TextBox runat="server" ID="txtRemoveUser" CssClass="form-control" />
</div>
</div>
<div class="form-group">
<asp:Label runat="server" CssClass="col-sm-offset-2 col-sm-3 control-label">
<b>Request For</b>
</asp:Label>
<div class="col-sm-3">
<label class="radio-inline">
<asp:RadioButton runat="server" ID="rbRemoveYourself" GroupName="RemoveRequestFor" /> Myself
</label>
<label class="radio-inline">
<asp:RadioButton runat="server" ID="rbRemoveOtherUser" GroupName="RemoveRequestFor" /> Other user
</label>
</div>
</div>
<div class="row">
<div class="col-sm-offset-8 col-sm-3" style="padding-left: 0px">
<asp:Button ID="btnRemoveUser" runat="server" Text="Remove From The List" CssClass="btn btn-danger" ToolTip="Click to remove the specified user from the payday lunch list." />
</div>
</div>
There you go! a new function has been added to disable the button and will be called on blur for text box and on change for radio buttons.
HTML
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="txtRemoveUser" CssClass="col-sm-offset-2 col-sm-3 control-label">Enter Name To Be Removed</asp:Label>
<div class="col-sm-3">
<asp:TextBox runat="server" ID="txtRemoveUser" CssClass="form-control" />
</div>
</div>
<div class="form-group">
<asp:Label runat="server" CssClass="col-sm-offset-2 col-sm-3 control-label">
<b>Request For</b>
</asp:Label>
<div class="col-sm-3">
<label class="radio-inline">
<asp:RadioButton runat="server" ID="rbRemoveYourself" GroupName="RemoveRequestFor" /> Myself
</label>
<label class="radio-inline">
<asp:RadioButton runat="server" ID="rbRemoveOtherUser" GroupName="RemoveRequestFor" /> Other user
</label>
</div>
</div>
<div class="row">
<div class="col-sm-offset-8 col-sm-3" style="padding-left: 0px">
<asp:Button ID="btnRemoveUser" runat="server" Text="Remove From The List" CssClass="btn btn-danger" ToolTip="Click to remove the specified user from the payday lunch list." />
</div>
</div>
JavaScript
<script>
$(document).ready(function () {
$("#MainContent_btnRemoveUser").prop('disabled', true);
$("#MainContent_btnAddUser").prop('disabled', true);
});
$("#MainContent_txtRemoveUser").on("blur", function () {
disableButton();
});
$("#MainContent_rbRemoveYourself").change(function () {
disableButton();
});
$("#MainContent_rbRemoveOtherUser").change(function () {
disableButton();
});
// Disables 'Remove' button unless all fields popluted
function disableButton() {
var isRbRemoveSelfChecked = $("#MainContent_rbRemoveYourself").is(':checked')
var isRbRemoveOtherChecked = $("#MainContent_rbRemoveOtherUser").is(':checked')
if ($('#MainContent_txtRemoveUser').val() != '' && (isRbRemoveSelfChecked || isRbRemoveOtherChecked)) {
$("#MainContent_btnRemoveUser").prop('disabled', false);
}
else {
$("#MainContent_btnRemoveUser").prop('disabled', true);
}
}
</script>
This should give you the expected result:-
$('input[name="RemoveRequestFor"]').change(function () {
if($("#MainContent_txtUsername").val().trim() != "")
$("#MainContent_btnAddUser").prop('disabled', false);
});
$("#MainContent_txtUsername").blur(function () {
if($('input[name="RemoveRequestFor"]:checked').length > 0)
$("#MainContent_btnAddUser").prop('disabled', false);
});
Also, you can use keyup function instead of blur to make your form more responsive.
Try replacing if ($('#MainContent_txtUsername').val()) with
if ($('#MainContent_txtUsername').val() != '')
For radio button, don't check any condition on onchange and write same logic.
Related
I have a RadioButtonList inside a repeater and I want to clear the checked value on the OnChange of a textbox
<asp:Repeater ID="QuestionsRpt" runat="server">
<HeaderTemplate>
<div class="form-horizontal form-condensed">
</HeaderTemplate>
<ItemTemplate>
<div class="form-group">
<label class='col-sm-6 control-label' style="text-align:left"><span id="Question" runat="server"><%# Eval("Name_" + UserLanguage.ToUpper()) %></span> <i class="fa fa-question-circle" runat="server" visible='<%# Eval("Description_" + UserLanguage.ToUpper()).ToString() != ""%>' data-toggle="tooltip" title='<%# Eval("Description_" + UserLanguage.ToUpper()).ToString()%>'></i></label>
<div class="col-sm-6">
<asp:RadioButtonList ID="RadioButtonList" runat="server" CssClass="RadioButtonList" AutoPostBack="true"
DataSource='<%# (Eval("ListOfChoice_" + UserLanguage.ToUpper()).ToString()).Split(";".ToCharArray()) %>'
Visible='<%# (Convert.ToInt32(Eval("Type_IsSingleChoice")) == 1)%>'>
</asp:RadioButtonList>
<input type='text' id="OtherOptionTB" runat="server"
placeholder='<%# GetLocalResourceObject("Other Option") %>' class="form-control otherOption input-sm" value=''
autocomplete="off" visible='<%# Eval("AllowFreeText")%>' onchange="ResetRadioButtonList()"/>
</div>
</div>
<br />
</ItemTemplate>
<FooterTemplate>
</div>
</FooterTemplate>
Here is the jquery:
<script type="text/javascript">
function ResetRadioButtonList() {
$(event.target).closest('.form-group').find('.RadioButtonList').prop('checked', false);
}
When I log $(event.target).closest('.form-group').find('.RadioButtonList') I do get the the RadioButtonList but I can't seem to figure out how to clear it correctly.
I found the problem...
I need to access all the inputs in my RadioButtonList
Here is the updated Jquery:
function ResetRadioButtonList() {
$(event.target).closest('.form-group').find('.RadioButtonList').find('input:radio').prop('checked', false);}
I am working on Asp.net form as follows
<form runat="server" id="form">
<label>Select Category <span>*</span></label>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Mobiles</asp:ListItem>
<asp:ListItem>Electronics and Appliances</asp:ListItem>
<asp:ListItem>Cars</asp:ListItem>
<asp:ListItem>Bikes</asp:ListItem>
<asp:ListItem>Furniture</asp:ListItem>
<asp:ListItem>General</asp:ListItem>
</asp:DropDownList>
<div class="clearfix"></div>
<label>Ad Title <span>*</span></label>
<asp:TextBox ID="txt_title" class="phone" runat="server"></asp:TextBox>
<div class="clearfix"></div>
<label>Ad Description <span>*</span></label>
<%--<textarea class="mess" placeholder="Write few lines about your product"></textarea>--%>
<asp:TextBox ID="txt_Body" class="mess" placeholder="Write few lines about your product" TextMode="multiline" Style="resize: none" Width="770px" Height="150px" Wrap="true" runat="server" Font-Bold="True"></asp:TextBox>
<div class="clearfix"></div>
<div class="upload-ad-photos">
<label>Photos for your ad :</label>
<div class="photos-upload-view">
<asp:ImageButton ID="ImageButton1" UseSubmitBehavior="false" OnClientClick="return chooseFile();" ImageUrl="Images/Capture.JPG" runat="server" />
<asp:FileUpload ID="FileUploadControl" runat="server" Visible="False" />
<div id="messages">
<p>Status Messages</p>
</div>
</div>
<div class="clearfix"></div>
</div>
<div class="personal-details">
<label>Your Name <span>*</span></label>
<asp:TextBox ID="txt_name" class="name" runat="server"></asp:TextBox>
<div class="clearfix"></div>
<label>Your Mobile No <span>*</span></label>
<asp:TextBox ID="txt_phn" class="phone" runat="server"></asp:TextBox>
<div class="clearfix"></div>
<label>Your Email Address<span>*</span></label>
<asp:TextBox ID="txt_email" class="email" runat="server"></asp:TextBox>
<div class="clearfix"></div>
<p class="post-terms">By clicking <strong>post Button</strong> you accept our Terms of Use and Privacy Policy</p>
<asp:TextBox ID="post_sub" Text="Post" type="submit" runat="server"></asp:TextBox>
<div class="clearfix"></div>
</form>
Where I want to call a hidden fileupload when Imagebutton is clicked using JavaScript as follows:
<script type="text/javascript">
function chooseFile() {
document.getElementById("#FileUploadControl").click();
alert("grt");
return false;
}
</script>
But, I was not able to call the function instead page reloads, as you can see I am returning false in the function also. Please guide me to make this work.
You have set the Visible property of the FileUpload Control to false. Therefore it does not exist on the client side. The Visible property is not the same as display:none in HTML/CSS.
You should do something like this:
<span style="display: none">
<asp:FileUpload ID="FileUploadControl" runat="server" />
</span>
And it's always better to use the ClientID instead of hard coding the ID of the FileUpload Control.
<script type="text/javascript">
function chooseFile() {
document.getElementById("<%= FileUploadControl.ClientID %>").click();
return false;
}
</script>
When you use document.getElementById you shouldn't mention # since it already searches for id attribute, in your current state it will look for id #FileUploadControl which is not your element id. change your code to this:
function chooseFile() {
document.getElementById("FileUploadControl").click();
alert("grt");
return false;
}
<form runat="server" id="form">
<div class="photos-upload-view">
<img id="ImageButton1" OnClick="return chooseFile();" src="https://maxcdn.icons8.com/office/PNG/512/Computer_Hardware/mouse_left_click-512.png" style="widdth:40px;height:40px;" />
<input type="file" ID="FileUploadControl" runat="server" style="display:none;" />
</div>
</form>
Yes, number one is you using # of you document.getElementById("#FileUploadControl") it's wrong and you should use it without # document.getElementById("FileUploadControl").
second thing if you use Visible="False" attribute it not rendering the HTML element, without that you can use below two methods.
FileUploadControl.Style["visibility"] = "hidden" in your backend file
using following css class for hide
function chooseFile() {
document.getElementById("FileUploadControl").click();
alert("grt");
return false;
}
.setDisplayNone {
display:none;
}
<asp:FileUpload ID="FileUploadControl" runat="server" CssClass="setDisplayNone" />
I have an asp.net contact us form which has 'Tel No.' and 'Email' fields. What i'm after is one error message for if both these fields are blank when the form is submitted but i can't figure it out, brain fart i think lol
HTML
<div class="form-group">
<asp:Label ID="TelFieldLabel" class="col-md-3 control-label" runat="server" Text="Contact No." AssociatedControlID="TelField"></asp:Label>
<div class="col-md-3">
<asp:TextBox ID="TelField" runat="server" class="form-control" type="Number"></asp:TextBox>
</div>
</div>
<div class="form-group">
<asp:Label ID="EmailFieldLabel" class="col-md-3 control-label" runat="server" Text="Email address" AssociatedControlID="EmailField"></asp:Label>
<div class="col-md-3">
<asp:TextBox ID="EmailField" runat="server" class="form-control" type="Text"></asp:TextBox>
</div>
<div class="col-md-offset-3 col-md-9">
<asp:RegularExpressionValidator Display="Dynamic" runat="server" ID="RegularExpressionValidator1" SetFocusOnError="True" ForeColor="Red" ControlToValidate="EmailField" ErrorMessage="RegularExpressionValidator" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*">Email address is not a valid format.</asp:RegularExpressionValidator>
<asp:CustomValidator id="CustomValidator2" runat="server" Display="Dynamic" ForeColor="Red" ErrorMessage="Please enter either a phone number of an email address." ClientValidationFunction="ContactFields_ClientValidate" OnServerValidate="PrefContact_ServerValidate" />
</div>
</div>
div class="form-group">
<div class="col-xs-12">
<div class="pull-right">
<asp:LinkButton ID="SubmitButton" runat="server" OnClick="SubmitButton_Click" CssClass="btn btn-primary" OnClientclick="ShowProcessingPopup();"><span class="glyphicon glyphicon-ok"></span> Submit</asp:LinkButton>
</div>
</div>
</div>
My email address also hase a validation error assigned to it as you can see from the abve.
ASP.NET way to do it is,
Markup
<asp:CustomValidator ID="CustomValidator2" runat="server"
Display="Dynamic"
ForeColor="Red"
ErrorMessage="Please enter either a phone number of an email address."
ClientValidationFunction="ContactFields_ClientValidate"
OnServerValidate="CustomValidator2_ServerValidate">
JavaScript
function ContactFields_ClientValidate(source, arguments) {
var telephoneField = document.getElementById("<%= TelField.ClientID %>");
var emailField = document.getElementById("<%= EmailField.ClientID %>");
if (telephoneField.value == "" && emailField.value == "") {
arguments.IsValid = false;
}
else {
arguments.IsValid = true;
}
}
Code-Behind
protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
{
if (TelField.Text.Trim() == "" && EmailField.Text.Trim() == "")
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
New in ASP.net and i want to set the validation first before it goes to the Codebehind in my asp program, because the fields does'nt validate after clicking the button inside ASP:Content
Heres my Shortcode:
<asp:Content ID="Content2" runat="server" ContentPlaceHolderID="MainContent" CssClass="bodyForm">
<section id="content" role="main">
<div class="entry two_third">
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('#contactform').validationEngine('init');
jQuery('#contactform #contact_form_formsend').click(function () {
alert("He Goes Here!");
var form_builder_url = jQuery('#contact_form_url').val();
jQuery('#Content2 .loading').animate({ opacity: 1 }, 250);
if (jQuery('#Content2').validationEngine('validate')) {
jQuery.post(form_builder_url, {
contact_name: jQuery('.txtName').val(),
contact_email: jQuery('.txtEmail').val(),
contact_subject: jQuery('.txtSubject').val(),
contact_message: jQuery('.txtaMessage').val(),
formname: 'Content2',
formtype: 'contactf'
}, function () {
jQuery('#Content2 .loading').animate({ opacity: 0 }, 250);
document.getElementById('Content2').reset();
jQuery('#Content2').parent().find('.box').hide();
jQuery('#Content2').parent().find('.success_box').fadeIn('fast');
jQuery('html, body').animate({ scrollTop: jQuery('#Content2').offset().top - 100 }, 'slow');
jQuery('#Content2').parent().find('.success_box').delay(5000).fadeOut(1000);
});
return false;
} else {
jQuery('#Content2 .loading').animate({ opacity: 0 }, 250);
return false;
}
});
});
</script>
<form action="#" method="post" id="contactform">
<asp:Label ID="lblSuccess" runat="server" Text=""></asp:Label>
<br />
<p>Required fields are marked <span class="color_3">*</span></p>
<div class="form_info cmsms_input">
<label for="contact_name">Name <span class="color_3">*</span></label>
<div class="form_field_wrap">
<input type="text" name="contact_name" runat="server" id="txtName" value="" size="22" tabindex="3" class="txtName validate[required,minSize[3],maxSize[100],custom[onlyLetterSp]]"/>
</div>
</div>
<div class="cl"></div>
<div class="form_info cmsms_input">
<label for="contact_email">Email <span class="color_3">*</span></label>
<div class="form_field_wrap">
<input type="text" name="contact_email" runat="server" id="txtEmail" value="" size="22" tabindex="4" class="txtEmail validate[required,custom[email]]" />
</div>
</div>
<div class="cl"></div>
<div class="cl"></div>
<div class="form_info cmsms_input">
<label for="contact_subject">Subject <span class="color_3">*</span></label>
<div class="form_field_wrap">
<input type="text" name="contact_subject" runat="server" id="txtSubject" value="" size="22" tabindex="6" class="txtSubject validate[required,minSize[3],maxSize[100]]" />
</div>
</div>
<div class="cl"></div>
<div class="form_info cmsms_textarea">
<label for="contact_message">Message <span class="color_3">*</span></label>
<div class="form_field_wrap">
<textarea name="contact_message" runat="server" id="txtaMessage" cols="28" rows="6" tabindex="7" class="txtaMessage validate[required,minSize[3]]" ></textarea>
</div>
</div>
<div class="cl"></div>
<div class="cl"></div>
<div>
<asp:Button class="more_button fl" runat="server" tabindex="8" Text="Send a message"
ID="contact_form_formsend" onclick="btnSendEmail_Click" /></div>
<div class="loading">
</div>
</form>
</div>
</div>
</section>
</asp:Content>
Here as you can see, My problem is that it goes forward the the codebehind and submit the form even before validating the page which I encounter Errors because of null fields, Hope Someone with Golden heart help me in this problem. . Thanks in Advance
You can call javascript function before postback. OnClientClick is use to call javascript function before postback. Use following code for reference:
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" ToolTip="Save" OnClientClick="return CheckValidation()" />
Call CheckValidation() javascript function. It will postback if function returns true.
<script type="text/javascript">
function CheckValidation()
{
// do validations here and return true if validate and return false if not
}
</script>
I am trying to use a customvalidator to validate a DIV form and then close it if there is no validation errors. Below is my code, I can't get my custom validator to work, when I click submit, nothing validates, not sure what's wrong. Please advice. Thanks.
function validateRedemptionDialog(src, args) {
var rDate = document.getElementById('<%=uitxtRedemptionDate.ClientID%>').value;
if (rDate == "") {
args.IsValid = false;
return;
}
args.IsValid = true;
}
function closeRedemptionDialog() {
$('#dialog_Active_Redemption_confirm').dialog('close');
}
<div id="dialog_Active_Redemption_confirm" style="display: none">
<div class="section_body">
<div class="section_body_content">
<div class="row">
<asp:Label runat="server" ID="uilblRedemptionDate" Text="<%$ Resources:MembersNContactsManagerResources, uigrdhdrTransDate %>"
CssClass="label">
</asp:Label>
<asp:TextBox ID="uitxtRedemptionDate" runat="server" CssClass="text DatePicker" Style="width: 120px;
margin-right: 2px;">
</asp:TextBox>
<asp:CustomValidator ID="ctvtxtCamDateEnd" runat="server" ClientValidationFunction="validateRedemptionDialog"
ControlToValidate="uitxtRedemptionDate" ErrorMessage='<img src="../Images/icons/error.png" style="vertical-align:middle"/> XXX!'
Font-Names="arial" Font-Size="X-Small" SetFocusOnError="True" Display="Dynamic" />
</div>
<div class="row">
<asp:Label runat="server" ID="uilblRedemptionAmountSpent" Text="<%$ Resources:MembersNContactsManagerResources, uilblRedemptionAmountSpent %>"
CssClass="label">
</asp:Label>
<asp:TextBox ID="uitxtRedemptionAmountSpent" runat="server" Style="width: 120px;">
</asp:TextBox>
</div>
<div class="row">
<ul class="inline" style="margin-left: 137px; padding: 3px;">
<li><span class="button grey_btn">
<%--Submit button--%>
<asp:Button ID="uibtnRedemption" runat="server" Text="<%$ Resources : MembersNContactsManagerResources, uilblSubmit %>" OnClientClick="javascript:closeRedemptionDialog();"/>
<span> </span> </span></li>
</ul>
</div>
</div>
</div>
</div>
The validator will not validate empty text with your current configuration.
Set ValidateEmptyText to true if you need it to fire even when the user has entered nothing.
A CustomValidator does not need to have a ControlToValidate. If you need to validate in any case, you should leave that property empty.