locked
hide or display FILEUPLOAD CONTROL depends on dropdown value RRS feed

  • Question

  • User987660975 posted

    Hi,

    How to hide or display file upload control?

    Field upload control should be displayed if drop down value is type1 otherwise it should be hidden.

    File upload control is displaying when I select drop down value is type1 but it is not hiding when I select drop down value type2.

    Please let me know how to fix it. Any help would be greatly appreciated.

    see my code:

    <script>

     function change() {
                if (document.getElementById("<%= ddlType.ClientID %>").value == "type1") {
                    document.getElementById("<%= fileUpload.ClientID %>").style.display = 'none';
                   
                }
                else {
                    document.getElementById("<%= fileUpload.ClientID %>").style.display = 'block';
                   
                }
            }

    </script>                              

    asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
        <div id="ui-dialog-message">
        </div>
        <div id="divRequestForm" class="MainForm">
            <table width="100%">

    <tr>
                    <td>
                        Type
                    </td>

                    <td>
                        <asp:DropDownList ID="ddlType" runat="server" Width="100%" CssClass="NormalSelect" onChange="change()">
                        </asp:DropDownList>
                    </td>
                    <td>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="Server" ErrorMessage=" Must enter Type" ControlToValidate="ddlType"
                            Display="dynamic" CssClass="ValidationError"></asp:RequiredFieldValidator>

                    </td>
                </tr>
                <tr>
                    <td >
                        Attachment
                    </td>
                    <td>
                        <asp:FileUpload ID="fileUpload" runat="server" CssClass="NormalSelect" style="display:none;"></asp:FileUpload>
                    </td>

                    <td>
                        &nbsp;
                    </td>
                </tr>

    </asp>

    Thursday, April 26, 2018 3:36 PM

Answers

  • User-369506445 posted

    your problem is about your binding

    ddl.DataTextField = "Description";
    ddl.DataValueField = "Value";

    change to

    ddl.DataTextField = "Description";
    ddl.DataValueField = "Description";

    also before do above change you can put a alert in your java-script and get drop-down list value

    function change() {
                alert(document.getElementById("<%= ddlType.ClientID %>").value);
                if (document.getElementById("<%= ddlType.ClientID %>").value == "type1") {
                    document.getElementById("<%= fileUpload.ClientID %>").style.display = 'none';
                   
                }
                else {
                    document.getElementById("<%= fileUpload.ClientID %>").style.display = 'block';
                   
                }
            }

    please try two note and tell me your result

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 27, 2018 4:26 PM

All replies

  • User-369506445 posted

    hi

    please try my code first and if was correct then change to your nedd

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    
    
        <script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
    
        <script>
    
            function change() {
                if (document.getElementById("<%= ddlType.ClientID %>").value == "type1") {
                    document.getElementById("<%= fileUpload.ClientID %>").style.display = 'none';
                }
                else {
                    document.getElementById("<%= fileUpload.ClientID %>").style.display = 'block';
                }
            }
    
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div id="ui-dialog-message">
            </div>
            <div id="divRequestForm" class="MainForm">
                <table width="100%">
    
                    <tr>
                        <td>Type
                        </td>
    
                        <td>
                            <asp:DropDownList ID="ddlType" runat="server" Width="100%" CssClass="NormalSelect" onChange="change()">
                                <asp:ListItem Text="type2" Value="type2" />
                                <asp:ListItem Text="type1" Value="type1" />
                            </asp:DropDownList>
                        </td>
                        <td>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="Server" ErrorMessage=" Must enter Type" ControlToValidate="ddlType"
                                Display="dynamic" CssClass="ValidationError"></asp:RequiredFieldValidator>
    
                        </td>
                    </tr>
                    <tr>
                        <td>Attachment
                        </td>
                        <td>
                            <asp:FileUpload ID="fileUpload" runat="server" CssClass="NormalSelect" Style="display: none;"></asp:FileUpload>
                        </td>
    
                        <td>&nbsp;
                        </td>
                    </tr>
                </table>
            </div>
        </form>
    </body>
    </html>
    

    Thursday, April 26, 2018 3:52 PM
  • User987660975 posted

    Hi Vahid,

    It is working for list options but it is not working if I populate drop down values from SQL table.

    Any suggestions?

    Thanks

    Thursday, April 26, 2018 5:51 PM
  • User-369506445 posted

    Yes.i think you have a problem to bind database result to dropdown . Please put your code for fetch from database and bind to dropdown here

    Thursday, April 26, 2018 5:55 PM
  • User-369506445 posted

    i think your problem is about your drop-down binding.In this line

     ddlType.DataTextField = "Type";
     ddlType.DataValueField = "ID";

    and in your script use

      if (document.getElementById("<%= ddlType.ClientID %>").value == "type1") {

    that if not work , because value is ID and it's different from text in drop-down.

    please change your script to below script :

    <script>
             function change() {
                 var e = document.getElementById("<%= ddlType.ClientID %>");
    
                if (e.options[e.selectedIndex].text == "type1") {
    
                    document.getElementById("<%= fileUpload.ClientID %>").style.display = 'none';
                }
                else {
                    document.getElementById("<%= fileUpload.ClientID %>").style.display = 'block';
                }
            }
    
        </script>

    also i create a  full sample for fetch from database and bind to drop-down

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
         <script>
             function change() {
                 var e = document.getElementById("<%= ddlType.ClientID %>");
    
                if (e.options[e.selectedIndex].text == "type1") {
    
                    document.getElementById("<%= fileUpload.ClientID %>").style.display = 'none';
                }
                else {
                    document.getElementById("<%= fileUpload.ClientID %>").style.display = 'block';
                }
            }
    
        </script>
        
    </head>
    <body>
        <form id="form1" runat="server">
             <div id="ui-dialog-message">
            </div>
            <div id="divRequestForm" class="MainForm">
                <table width="100%">
    
                    <tr>
                        <td>Type
                        </td>
    
                        <td>
                            <asp:DropDownList ID="ddlType" runat="server" Width="100%" CssClass="NormalSelect" onChange="change()">
                                
                            </asp:DropDownList>
                        </td>
                        <td>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="Server" ErrorMessage=" Must enter Type" ControlToValidate="ddlType"
                                Display="dynamic" CssClass="ValidationError"></asp:RequiredFieldValidator>
    
                        </td>
                    </tr>
                    <tr>
                        <td>Attachment
                        </td>
                        <td>
                            <asp:FileUpload ID="fileUpload" runat="server" CssClass="NormalSelect" Style="display: none;"></asp:FileUpload>
                        </td>
    
                        <td>&nbsp;
                        </td>
                    </tr>
                </table>
            </div>
        </form>
    </body>
    </html>
    protected void Page_Load(object sender, EventArgs e)
            {
                 DataTable subjects = new DataTable();
    
                 using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStringDb"].ConnectionString))
                {
    
                    try
                    {
                        SqlDataAdapter adapter =
                            new SqlDataAdapter("SELECT Id, [Type] FROM [Table]", con);
                        adapter.Fill(subjects);
    
                        ddlType.DataSource = subjects;
                        ddlType.DataTextField = "Type";
                        ddlType.DataValueField = "ID";
                        ddlType.DataBind();
                    }
                    catch (Exception ex)
                    {
                        // Handle the error
                    }
                }
    
            }

    Friday, April 27, 2018 7:21 AM
  • User753101303 posted

    Hi,

    Use "view source" in your browser to see your HTML markup or use the debugger to see which value you have. More likely your drop down doesn't use the expected values.

    Friday, April 27, 2018 7:38 AM
  • User987660975 posted

    Thank you Vahid.

    I am using entity framework and here s my code and let me know if I am doing wrong.

    public partial class RequestForm : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    //If the page is loading for the first time and is not a PostBack
    if(!Page.IsPostBack)
    {
    //If the Page.User is not null (meaning there is a valid autheticated user accessing the page)
    if (User != null)
    {
    string displayName = string.Empty;
    string emailAddress = string.Empty;

    //Call function to get the Page.User's display name and email address from Active Directory
    if(UtilityFunctions.GetADUserNameAndEmail(User.Identity.Name, out displayName, out emailAddress))
    {
    //Set the Requestor Name and Requestor Email textbox fields to default values based on the Page.User
    //creating the new Reqeust
    txtRequestorName.Text = displayName;
    txtRequestorEmail.Text = emailAddress;
    }

    }
    //Populate the Department Dropdown control from the database LOV table using the Category "DEPARTMENT" as a filter
    UtilityFunctions.PopulateControlFromLOV(ddlDepartment, "DEPARTMENT");
    //Set the Compare Validator value for the "Date Required" textbox to 2 weeks (14 days) from Today
    compValidatorDateRequired.ValueToCompare = DateTime.Today.AddDays(14).ToShortDateString();
    //Set Focus to Store ID text box
    txtStoreID.Focus();


    //Populate the Type Dropdown control from the database LOV table using the Category "TYPE" as a filter
    UtilityFunctions.PopulateControlFromLOV(ddlType, "TYPE");


    }

    }

    public static void PopulateControlFromLOV(DropDownList ddl, string category)
    {
    ddl.DataTextField = "Description";
    ddl.DataValueField = "Value";
    ddl.Font.Name = "Futura-Book";
    ddl.Font.Size = 9;
    using (var context = new RMKTEntities())
    {
    var choices = (from c in context.LOVs
    where c.Category == category
    orderby c.SortOrder
    select c).ToList();

    ddl.DataSource = choices;
    ddl.DataBind();
    ddl.Items.Insert(0, "");

    }
    }

    Friday, April 27, 2018 2:40 PM
  • User-369506445 posted

    your problem is about your binding

    ddl.DataTextField = "Description";
    ddl.DataValueField = "Value";

    change to

    ddl.DataTextField = "Description";
    ddl.DataValueField = "Description";

    also before do above change you can put a alert in your java-script and get drop-down list value

    function change() {
                alert(document.getElementById("<%= ddlType.ClientID %>").value);
                if (document.getElementById("<%= ddlType.ClientID %>").value == "type1") {
                    document.getElementById("<%= fileUpload.ClientID %>").style.display = 'none';
                   
                }
                else {
                    document.getElementById("<%= fileUpload.ClientID %>").style.display = 'block';
                   
                }
            }

    please try two note and tell me your result

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 27, 2018 4:26 PM
  • User987660975 posted

    Thank you for your suggestion.

    it's resolved my issue. I did update the function instead of updating the binding as there are some other values depend on "ddl.DataValueField = "Value";
    In function I used value instead of description. now my function is:
    function change() {
    if (document.getElementById("<%= ddlType.ClientID %>").value == "201") {
    document.getElementById("<%= fileUpload.ClientID %>").style.display = 'block';
    }
    else { document.getElementById("<%= fileUpload.ClientID %>").style.display = 'none';

    }
    }
    Friday, April 27, 2018 7:19 PM
  • User987660975 posted

    Hi Vahid,

    one more question.

    How to make fileupload control is required?

    thx.

    Saturday, April 28, 2018 5:43 AM
  • User-369506445 posted

    please try below code :

    <asp:FileUpload ID="fileUpload" runat="server" />
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                ControlToValidate="fileUpload" ErrorMessage="File Required!">
            </asp:RequiredFieldValidator>
            <br />
            <asp:Button ID="Button1" runat="server" Text="Upload" />

    Saturday, April 28, 2018 5:57 AM
  • User987660975 posted

    Thank you Vahid but it is not working. i am trying to validate using javscript.

    Attachment is requirde if dropdown value is 201. please advise.

    here is my code:

    <tr>
    <td>
    Type
    </td>

    <td>
    <asp:DropDownList ID="ddlType" runat="server" Width="100%" CssClass="NormalSelect" onChange="change()">
    </asp:DropDownList>
    </td>
    <td>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="Server" ErrorMessage=" Must enter Request Type" ControlToValidate="ddlType"
    Display="dynamic" CssClass="ValidationError"></asp:RequiredFieldValidator>

    </td>
    </tr>
    <tr>
    <td >
    Attachment
    </td>
    <td>
    <asp:FileUpload ID="fileUpload" runat="server" CssClass="NormalSelect" style="display:none"></asp:FileUpload>
    <asp:RequiredFieldValidator ID="uploadFileRequired" runat="Server" ControlToValidate="fileUpload" ClientValidationFunction="uploadFile_Validate"
    Display="Dynamic" Text=" Upload file *" CssClass="ValidationError" ValidateEmptyText="true" />
    </td>
    </td>

    Saturday, April 28, 2018 6:12 AM
  • User-369506445 posted

    i create a sample for validate with jquery , please , First try my code in clear project  and if was correct then change to your needs

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    
        <script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
        <script>
            jQuery(function ($) {
                $('#my-form').validate({
                    rules: {},
                    messages: {},
                    submitHandler: function () {
                        return false
                    }
                });
                $('input[name^="fileupload"]').rules('add', {
                    required: true,
                    accept: "image/jpeg, image/pjpeg"
                })
            })
        </script>
    </head>
    <body>
        <form id="my-form">
            <input type="file" required="" name="fileupload1" id="fileupload1" />
            <input type="submit" value="save" />
        </form>
    </body>
    </html>

    Saturday, April 28, 2018 6:31 AM
  • User987660975 posted

    Thank you Vahid.

    Mine is aspx page. I tried using javascript but not getting expected results.

    In my above code file upload is required when it is not hidden.

    Saturday, April 28, 2018 12:38 PM
  • User987660975 posted

    Hi Vahid,

    Never mind. I was able to fix the issue.

    Here is my code for others reference.

    <td>
    <asp:FileUpload ID="fileUpload" runat="server" CssClass="NormalSelect" style="display:none"></asp:FileUpload>
    <asp:CustomValidator ID="CustomValidator2" ControlToValidate="fileUpload" ClientValidationFunction="fileUploade_Validate"
    Display="Dynamic" runat="server" Text=" Upload file *"
    CssClass="ValidationError" ValidateEmptyText="true" />
    </td>

    <td>

    function fileUploade_Validate(source, args) {
    var control_ddlID = $("#<%= ddlType.ClientID %>").val();
    var control_fileUploadID = $("#<%= fileUpload.ClientID %>").val();
    if ((control_ddlID == '201') && (control_fileUploadID == '')) {
    args.IsValid = false;
    return;
    }
    if ((control_ddlID == '201') && (control_fileUploadID == '')) {
    args.IsValid = false;
    return;
    }

    args.IsValid = true;
    return;
    }

    Saturday, April 28, 2018 2:35 PM