How to select minimum three files in multiple file upload Control
Should i Add AJAX FILE UPLOAD CONTROL TOOL KIT
I want to select minimum three files for file upload control, and when i select less then three file then i want a alert message on client side itself.Where Should i change in my existing code?
Where i am doing wrong please guide me:
My code in aspx:
<label>Root Cause Image<span style="color: #ff0000;">*</span></label>
<asp:FileUpload ID="FileUpload_RootCause" runat="server"
accept=".png,.jpg,.jpeg,.gif"
multiple="multiple"
type="file"
name="image[]" />
<asp:RegularExpressionValidator ID="rev1" runat="server"
ControlToValidate="FileUpload_RootCause"
required="This Field is Required"
ErrorMessage="Only JPG and PNG are allowed"
ValidationExpression=".*((\.jpg)|(\.JPG)|(\.png)|(\.PNG))"
CssClass="red">
</asp:RegularExpressionValidator>
<script>
$("#FileUpload_RootCause").on("change", function ()
{
if ($("#FileUpload_RootCause")[0].files.length < 3)
{
alert("You have to select minimum 3 images to proceed Further");
}
else
{
$("#imageUploadForm").submit();
}
});
</script>
Above code is not working at all don't know why?, i tried 2nd approach i tried something like this
And i am getting same thing as previous its not firing any alert message why ? and where i am doing wrong
<asp:FileUpload ID="FileUpload_RootCause" runat="server"
accept=".png,.jpg,.jpeg,.gif" AllowMultiple="true" />
<script>
function ValidateFile2() {
var fileCount =
document.getElementByID('FileUpload_RootCause').files.length;
if (fileCount < 3)
{
alert("Please select minimum 3 images..!!!");
return false;
}
else if (fileCount <= 0)
{
alert("Please select at-list 1 image..!!!");
return false;
}
return true;
}
</script>
Please check below code, it is working just check it.
<%# Page Title="About" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="WebApplication3.About" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<label>Root Cause Image<span style="color: #ff0000;">*</span></label>
<asp:FileUpload ID="FileUpload_RootCause" runat="server"
accept=".png,.jpg,.jpeg,.gif"
multiple="multiple"
type="file"
name="image[]" />
<asp:RegularExpressionValidator ID="rev1" runat="server"
ControlToValidate="FileUpload_RootCause"
required="This Field is Required"
ErrorMessage="Only JPG and PNG are allowed"
ValidationExpression=".*((\.jpg)|(\.JPG)|(\.png)|(\.PNG))"
CssClass="red">
</asp:RegularExpressionValidator>
<script>
$(document).ready(function () {
$("#MainContent_FileUpload_RootCause").on("change", function () {
if ($(this)[0].files.length < 3) {
alert("You have to select minimum 3 images to proceed Further");
}
else {
$("#imageUploadForm").submit();
}
});
});
</script>
</asp:Content>
I tried Something like this
<asp:FileUpload ID="FileUpload_RootCause" runat="server" accept=".png,.jpg,.jpeg,.gif" required="This Field is Required" AllowMultiple="true" onchange="Validate()"/>
<asp:RegularExpressionValidator ID="rev1" runat="server" ControlToValidate="FileUpload_RootCause" ErrorMessage="Only JPG and PNG are allowed" ValidationExpression=".*((\.jpg)|(\.JPG)|(\.png)|(\.PNG))" CssClass="red"></asp:RegularExpressionValidator>
<script >
function Validate() {
debugger;
var fileCount = document.getElementById("ContentPlaceHolder1_FileUpload_RootCause").files.length;
if (fileCount <3 ){
alert("You have to Select Minimum 3 images to Proceed Further");
document.getElementById("ContentPlaceHolder1_FileUpload_RootCause").value = null;
}
}
</script>
Related
I have an ASP Webform website and one a page I have a checkboxlist which has an 'Other' option. When the user checks this checkbox, an additional textbox is displayed. All this is working fine but the issue I am having is that, if the user unchecks the checkbox, it doesn't clear it.
The below code shows what I have
$(function ()
{
$("input[name='ctl00$MainContent$Step04OtherField']").click(function ()
{
ToggleSection();
});
ToggleSection();
});
function ToggleSection()
{
if ($("#MainContent_Browsers_5").is(":checked"))
{
$("#Step04OtherFieldDiv").show();
document.getElementById("<%=reqStep04OtherFieldErrorMessage.ClientID%>").style.visibility = "visible";
document.getElementById("<%=reqStep04OtherFieldErrorMessage.ClientID%>").enabled = true;
}
else
{
$("#Step04OtherFieldDiv").hide();
$("#MainContent_Step04OtherField").val("");
document.getElementById("<%=reqStep04OtherFieldErrorMessage.ClientID%>").style.visibility = "hidden";
document.getElementById("<%=reqStep04OtherFieldErrorMessage.ClientID%>").enabled = false;
}
}
HTML for checkboxlist
<div class="row">
<div class="col-xs-offset-0 col-sm-offset-5 col-sm-2">
<asp:CheckBoxList runat="server" id="Browsers" CssClass="CheckboxList">
<asp:ListItem Text="All browsers" Value="All browsers"></asp:ListItem>
<asp:ListItem Text="Internet explorer (IE)" Value="Internet explorer (IE)"></asp:ListItem>
<asp:ListItem Text="Firefox (FF)" Value="Firefox (FF)"></asp:ListItem>
<asp:ListItem Text="Chrome" Value="Chrome"></asp:ListItem>
<asp:ListItem Text="Safari" Value="Safari"></asp:ListItem>
<asp:ListItem Text="Other" Value="Other"></asp:ListItem>
</asp:CheckBoxList>
</div>
</div>
<div class="row">
<div class="col-xs-offset-0 col-sm-offset-4 col-sm-8">
<asp:CustomValidator Display="Dynamic" runat="server" ID="custBrowserCheckboxselected" ForeColor="Red" ErrorMessage="Please select at least one browser for us to check the website on." ClientValidationFunction="BrowserCheckbox_ClientValidate" />
</div>
</div>
<div class="form-group" id="Step04OtherFieldDiv">
<asp:Label ID="Step04OtherFieldLabel" class="col-sm-4 control-label" runat="server" Text="Please specify *" AssociatedControlID="Step04OtherField"></asp:Label>
<div class="col-sm-4">
<asp:TextBox ID="Step04OtherField" runat="server" class="form-control" style="max-width: 100%" TextMode="MultiLine" Rows="5"></asp:TextBox>
</div>
<div class="col-sm-offset-4 col-sm-8">
<asp:RequiredFieldValidator Display="Dynamic" runat="server" ID="reqStep04OtherFieldErrorMessage" SetFocusOnError="true" ForeColor="Red" ControlToValidate="Step04OtherField" ErrorMessage="Please all browsers you would like the website checked on." />
</div>
</div>
But the $("#MainContent_Step04OtherField").val("") doesn't seem to be working.
Also if there a better way of writing the above I'm up for that as I think it's a little messy but I couldn't get it working any other way; as it's a checkboxlist I could add individual ids to each one.
I believe you are binding the click event to the textbox instead of the checkbox.
This code works:
$(function() {
$("#chk").click(function() {
ToggleSection();
});
ToggleSection();
});
function ToggleSection() {
var $txt = $("#txt"); // Save textbox's reference
// The right way to check if a checkbox is checked is with .prop method
if ($("#chk").prop("checked")) {
$txt.prop("disabled", false);
}
else {
$txt.prop("disabled", true).val("");
}
}
Test it here.
In the example I enable / disable the field so that you can see that the value is clear. Here it is the code to show / hide:
var $chk;
$(function() {
$("#checks :checkbox").each(function() {
if ($(this).val() == "other")
$chk = $(this);
});
$chk.click(function() {
ToggleSection();
});
ToggleSection();
});
function ToggleSection() {
var $txt = $("#txt"); // Save textbox's reference
// The right way to check if a checkbox is checked is with .prop method
if ($chk.prop("checked")) {
$txt.show();
}
else {
alert("val: " + $txt.val());
$txt.hide().val("");
alert("val: " + $txt.val());
}
}
Fixed using the below code
$(document).ready(function ()
{
// Initially hide the 'Other' field row when page is loaded
if ($("#MainContent_Browsers_5").is(":checked"))
{
$('#Step04OtherFieldDiv').show();
}
else
{
$('#Step04OtherFieldDiv').hide();
}
$('#MainContent_Browsers_5').change(function ()
{
if (this.checked)
{
$('#Step04OtherFieldDiv').show();
document.getElementById("<%=reqStep04OtherFieldErrorMessage.ClientID%>").style.visibility = "visible";
document.getElementById("<%=reqStep04OtherFieldErrorMessage.ClientID%>").enabled = true;
}
else
{
$('#Step04OtherFieldDiv').hide();
document.getElementById("<%=reqStep04OtherFieldErrorMessage.ClientID%>").style.visibility = "hidden";
document.getElementById("<%=reqStep04OtherFieldErrorMessage.ClientID%>").enabled = false;
$("#MainContent_Step04OtherField").val('');
}
});
});
I'm working on a legacy .NET WebForms project where the front-end is being updated with Bootstrap.
There are some .NET Validation Controls which are validating on the ClientSide, but the "has-error" class needs to be added to the parent div of the input fields to match the Bootstrap markup.
Is there an event hook or a way of extending the .NET Validators so that I can add the "has-error" class to an invalid control group and remove it when valid?
e.g: Here is my markup which works server side:
<div class="form-group <%= IIf(RequiredFieldValidator1.IsValid, "has-error", "") %>">
<label class="control-label">Test</label>
<asp:TextBox runat="server" ID="TextBox1" CssClass="form-control" />
<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1"
ContolToValidate="TextBox1" ErrorMessage="TextBox1 is Required!" />
</div>
I was requiring the has-feedback class on the form-group div as well as the glyphicon tick and crosses depending on whether the input was valid or not. What I have found that works in my solution is to override asp.net's client side function ValidatorUpdateDisplay (note my code utilizes jQuery although you could use native JavaScript):
var originalValidatorUpdateDisplayMethod;
if (typeof(ValidatorUpdateDisplay) == "function"
&& typeof(originalValidatorUpdateDisplayMethod) != "function") {
originalValidatorUpdateDisplayMethod = ValidatorUpdateDisplay;
// now overwrite original method
ValidatorUpdateDisplay = function (val) {
originalValidatorUpdateDisplayMethod(val); // call original method first
var parent = $("#" + val.controltovalidate).parent();
if (parent.hasClass("form-group")) {
parent.addClass("has-feedback");
parent.toggleClass("has-success", val.isvalid);
parent.toggleClass("has-error", !val.isvalid);
var glyph = parent.find("span.form-control-feedback");
if (glyph.length == 0) {
glyph = $("<span class='glyphicon form-control-feedback' />");
parent.append(glyph);
}
glyph.toggleClass("glyphicon-ok", val.isvalid);
glyph.toggleClass("glyphicon-remove", !val.isvalid);
}
}
}
This adds the bootstrap validation to fields when they change as well as when an event on a control that has causesvalidation="true" is triggered.
Note: this is only adding the validations on the client side.
You'll need to put a id on the element
<div id="div1" class="someclass">
<img ... id="image1" name="image1" />
</div>
and this is the javascript which adds a class to a <div> element
var d = document.getElementById("div1");
d.className = d.className + " otherclass";
Here is what I did:
<asp:Panel ID="pnlNumberOnly" runat="server" CssClass="form-group">
<label for="<%= tbNumberOnly.ClientID %>" class="control-label">Enter a number:</label>
<asp:TextBox ID="tbNumberOnly" runat="server" CssClass="form-control" />
<asp:RegularExpressionValidator runat="server" ID="regExpNumberOnly"
ControlToValidate="tbNumberOnly"
Display="Dynamic"
ErrorMessage="Numbers only" CssClass="control-label"
ValidationExpression="^\d+$" EnableClientScript="True"/>
</asp:Panel>
and then my js looked like this:
$(document).ready(function() {
$('#<%= tbNumberOnly.ClientID %>').change(function() {
if ($('#<%= regExpNumberOnly.ClientID %>').is(':visible')) {
$('#<%= pnlNumberOnly.ClientID %>').addClass('has-error');
} else {
$('#<%= pnlNumberOnly.ClientID %>').removeClass('has-error');
}
});
});
I am using the ASP.NET PasswordRecovery method, and have a couple of CSS buttons to submit the form OR cancel the request.
I also grab the users email address to pass along to the successtext value of PasswordRecovery method, set the ASP hiddenvalue to success, and then try to use javascript to disable the buttons based on this value.
The problem is that this hiddenfield value seems to be set to "success" on initial page load, even though when viewing the source of the rendered page shows NO value.
There is probably a better approach to this, but I have tried several different ways, and this is successful up the point that I cant change the view state of the buttons.
<script runat="server">
protected void resetuserpassword_SendingMail(object sender, MailMessageEventArgs e)
{
e.Message.IsBodyHtml = true;
e.Message.Subject = "Password Assistance";
TextBox txtUserName = (TextBox)resetuserpassword.UserNameTemplateContainer.FindControl("UserName");
string UserEmailID = Membership.GetUser(txtUserName.Text.Trim()).Email;
resetuserpassword.SuccessText = "Password sent to ";
resetuserpassword.SuccessText += UserEmailID;
ValueHiddenField.Value = "Success";
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolderArea" Runat="Server">
<script type="text/javascript">
window.onload = disableButtons;
function disableButtons() {
var element = document.getElementById('ContentPlaceHolderArea_ValueHiddenField');
if (typeof(element) != 'undefined' && element != null) {
if (document.getElementById('ContentPlaceHolderArea_ValueHiddenField').value = 'Success') {
var submitBtnElement = document.querySelector("#submitBtn");
var cancelBtnElement = document.querySelector("#cancelBtn");
submitBtnElement.style.display = "none";
cancelBtnElement.style.display = "none";
}
}
}
function clickSubmit() {
document.getElementById("ContentPlaceHolderArea_resetuserpassword_UserNameContainerID_SubmitButton").click();
}
function clickCancel() {
window.location.replace("~/Login.aspx");
}
</script>
<asp:hiddenfield id="ValueHiddenField" value="" runat="server"/>
<asp:hiddenfield id="ValueHiddenField" value="" runat="server"/>
<asp:PasswordRecovery ID="resetuserpassword" runat="server"
MailDefinition-BodyFileName="~/ResetPasswordEmailTemplate.html"
OnSendingMail="resetuserpassword_SendingMail"
successtext="Password sent to email address on record."
Width="300px" Font-Names="Arial" Font-Size="Small" UserNameTitleText="" >
<InstructionTextStyle Font-Names="Arial" Font-Size="Small" />
<MailDefinition BodyFileName="~/ResetPasswordEmailTemplate.html"></MailDefinition>
<UserNameTemplate>
<div><asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName" style="display:none;"></asp:Label></div>
<div style="font: arial, verdana, sans-serif;font-size: 13px;padding-bottom: 5px;font-weight: bold;">Please Enter your Username</div>
<div><asp:TextBox ID="UserName" runat="server" style="width: 180px;"></asp:TextBox></div>
<div><asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="PasswordRecovery1">*</asp:RequiredFieldValidator></div>
<div><asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal></div>
<div style="display: inline;" ><asp:Button ID="SubmitButton" runat="server" CommandName="Submit" Text="Submit" ValidationGroup="PasswordRecovery1" style="display: none;" /></div>
</UserNameTemplate>
</asp:PasswordRecovery>
<div>
<div id="submitBtn" onclick="clickSubmit()">Submit</div>
<div id="cancelBtn" onclick="clickCancel()">Cancel</div>
</div>
</asp:Content>
Your javascript if statement is assigning the value 'Success' to the Hidden Field (single equals sign).
if (document.getElementById('ContentPlaceHolderArea_ValueHiddenField').value = 'Success') {
...
}
Change it to this (double equals sign):
if (document.getElementById('ContentPlaceHolderArea_ValueHiddenField').value == 'Success') {
...
}
I just recently started developing some parts of the ASP.NET project but I have very little experience of it. The problem is pretty much as described in a title of this question and here goes the code:
<script type="text/javascript" src="/scripts/hide.fields.js"></script>
<divs and divs...>
<asp:DropDownList class="dropdown expand" ID="EligibleUK" onchange="visaCheck(this.ListItem.GetValue());" runat="server">
<asp:ListItem
Enabled="True"
Text="Choose..."
Value=""
/>
<asp:ListItem
Enabled="True"
Text="Yes (UK/EU Cittizen)"
Value="Yes (UK/EU Cittizen)"
/>
<asp:ListItem
Enabled="True"
Text="Yes (Work Visa)"
Value="Yes (Work Visa)"
/>
<asp:ListItem
Enabled="True"
Text="No"
Value="No"
/>
</asp:DropDownList>
the content of my JS file:
function visaCheck(visa) {
if (visa === "Yes (Work Visa)"){
document.getElementById(visa1).style.display = "block";
document.getElementById(visa2).style.display = "block";
}else{
document.getElementById(visa1).style.display = "none";
document.getElementById(visa2).style.display = "none";
}
}
Now I tried different things in the html (.master strictly speaking) where I call the JS function code, such as:
this.ListItem
asp:ListItem
ListItem.Value
this.ListItem.Value
this.ListItem.Value()
this.ListItem.GetValue()
including the most obvious one (this.value) which worked with standard html file and in jsfiddle. Is there any specific way of doing it in ASP.NET? What am I missing and how do I fix this problem? Thanks for your answers.
Try changing:
<asp:DropDownList class="dropdown expand" ID="EligibleUK" onchange="visaCheck(this.options[this.selectdIndex].value);" runat="server">
I post an answer under my own question so it's more visible. I call js function with no argument and my javascript looks like this now:
function visaCheck() {
var visa = document.getElementById('Content_EligibleUK');
var selectedIndex = visa.selectedIndex;
var value = visa.options[selectedIndex].value
if (value === "Yes (Work Visa)"){
document.getElementById("visa1").style.display = "block";
document.getElementById("visa2").style.display = "block";
}else{
document.getElementById("visa1").style.display = "none";
document.getElementById("visa2").style.display = "none";
}
}
hope this helps some folks in the future :)
I am using twitter bootstrap validation class to get success and error in a text-box. I have two text boxes so when a user clicks on any text-box jquery should first check if the text-box is empty if its empty then red colour should appear around the box. When a user start entering data the text-box should change the colour to green. I would like to apply this technique across all the text-boxes. This is what I have done but when running a page it is not working?:
<div class="test">
<div class="form-group has-success">
</div>
</div>
<div class="form-group has-error">
</div>
<div id="pt" class="tab-pane active">
<asp:Label ID="label1" CssClass="form-group" runat="server" Text="Name:"></asp:Label>
<asp:TextBox ID="TextBox1" CssClass="form-control" runat="server" ></asp:TextBox>
<asp:Label ID="label2" CssClass="form-group" runat="server" Text="Surname:"></asp:Label>
<asp:TextBox ID="TextBox2" CssClass="form-control" runat="server"></asp:TextBox>
</div>
Jquery
$("TextBox").click(function () {
if ($.trim($('TextBox').val()) == "") {
$('.form-group has-error');
}
else if ($.trim($('TextBox').val()) != "") {
$('.form-group has-success');
}
});
This is the website i have used to get validation status: bootstrap example which i am following click here under form -> control status
try this:
$(function(){
$("#TextBox1").on("click", function(){
if($("#TextBox1").val().length === 0){
$("#TextBox1").parent().addClass("has-error");
}
});
$("#TextBox1").on("keydown", function(){
if($("#TextBox1").parent().hasClass("has-error")){
$("#TextBox1").parent().removeClass("has-error");
$("#TextBox1").parent().addClass("has-success");
}
});
$("#TextBox2").on("click", function(){
if($("#TextBox2").val().length === 0){
$("#TextBox2").parent().addClass("has-error");
}
});
$("#TextBox2").on("keydown", function(){
if($("#TextBox2").parent().hasClass("has-error")){
$("#TextBox2").parent().removeClass("has-error");
$("#TextBox2").parent().addClass("has-success");
}
});
});
Your HTML seems to be malformed.
I am not sure I understood correctly your question, but if you want to display the divs, then your code should work like that:
$("#tbDepartment").click(function () {
if ($.trim($('#tbDepartment').val()) == "") {
$('.form-group has-error').show();
}
else if ($.trim($('#tbDepartment').val()) != "") {
$('.form-group has-success').show();
}
});