The textbox is only enabled when a specific selection is made in the dropdown menu

My JavaScript code seems to be malfunctioning:

<script language="javascript" type="text/javascript">

    function ShowExpenseReport(Expense_Report_ID) {
        var width = screen.width;  
        var leftpad = (width - 740) / 2;
        var jsoption = "width=740,height=700,resizable=no,scrollbars=yes,toolbar=no,titlebar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no,left=" + leftpad + ",top=10";

        window.open("Documents/ExpenseReport.aspx?Expense_Report_ID=" + Expense_Report_ID, 'win02', jsoption);
        return false;
    }

    function changetextbox() {
        if (document.getElementById("ddlItem").value == '3') {
            document.getElementById("txtPurpose").disabled = 'true';
        } else {
            document.getElementById("txtPurpose").disabled = '';
        }
    }
</script>

This is the corresponding HTML code:

<asp:TemplateField HeaderStyle-CssClass="innerGridHeader" ItemStyle-CssClass="itemPadding"
    ItemStyle-Width="150px" HeaderStyle-VerticalAlign="Top" FooterStyle-VerticalAlign="Top">
    <HeaderTemplate>
        Item
    </HeaderTemplate>
    <ItemTemplate>
        <asp:Label ID="lblItem" Visible="false" runat="server" Text='<%#Eval("Item_Description") %>'></asp:Label>
        <asp:Label ID="lblItemID" Visible="false" runat="server" Text='<%#Eval("Item_ID") %>'></asp:Label>
        <asp:DropDownList ID="ddlItem" Width="140px" runat="server"  onChange="changetextbox()"  CssClass="combobox">
        </asp:DropDownList>
    </ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderStyle-CssClass="innerGridHeader" ItemStyle-CssClass="itemPadding"
    ItemStyle-Width="260px" HeaderStyle-VerticalAlign="Top" FooterStyle-VerticalAlign="Top">
    <HeaderTemplate>
        Purpose
    </HeaderTemplate>
    <ItemTemplate>
        <asp:Label ID="lblPurpose" runat="server" Width="240px" Text='<%#Eval("Purpose") %>'></asp:Label>
        <asp:TextBox ID="txtPurpose" runat="server" Width="240px" CssClass="inputbox" Text='<%#Eval("Purpose") %>'></asp:TextBox>
        <asp:RequiredFieldValidator ID="rfvPurpose" runat="server" ErrorMessage="Enter Purpose"
            ControlToValidate="txtPurpose" Display="None" ValidationGroup="NER" SetFocusOnError="True">
        </asp:RequiredFieldValidator>

        <asp:ValidatorCalloutExtender ID="vcePurpose" runat="server" TargetControlID="rfvPurpose"
            PopupPosition="BottomRight" WarningIconImageUrl="~/Library/Images/exclamation.png" />
    </ItemTemplate>
</asp:TemplateField>

The objective is to deactivate the textboxes when the user selects entertainment from the dropdown list with the value of 3 in the database.

Answer №1

One potential solution for your situation may involve disabling or enabling a textbox based on the value selected in a dropdown field. In ASP, a common approach to achieving this is outlined below:

onchange="DisableTextBox();"

<script language=javascript>
    function DisableTextBox() {
        var dropDown = document.getElementById('<%=DropDown.ClientID%>'); 

        if (dropDown.selectedIndex = ValueTocompare) {
            document.getElementById('<%=txtBoxID.ClientID%>').disabled = disabled;
        } else {
            document.getElementById('<%=txtBoxID.ClientID%>').disabled = '';
        }
    }
</script>

If this method does not achieve the desired outcome, you can also explore an alternative using this fiddle link: http://jsfiddle.net/SurajMindfire/zxvfcvq0/

Answer №2

Here is a helpful guide for you:

  1. The dropdown menu contains options for YES and NO values, with YES being the default selection.
  2. There is also a text box that will be enabled when the user selects YES from the dropdown. If the user selects NO, the text box will be disabled.
  3. An asterisk is used for validation of the text box.
function EnableDisableInputField(customerNarration) {
  var selectedValue = customerNarration.options[customerNarration.selectedIndex].value;
  var txtOther = document.getElementById("customisedNarration");
  txtOther.disabled = selectedValue == 'N' ? true : false;

  document.getElementById("asterisk").innerHTML = "";

  if (!txtOther.disabled) {
    txtOther.focus();
    document.getElementById("asterisk").innerHTML = "*";
  }
  var checkError = document.getElementById("customisedNarration_box").style = "display: none";
}
<div class="form-group ">
  <label class="floatinglabel"><sup class="text-red">*</sup> Customer Narration required</label>
  <div class="selectwrapper">
    <select class="form-control" id="customerNarration" name="customerNarration" onchange="EnableDisableInputField(this)" onfocus="hideerrmsgdelayed('customerNarration')">
      <option value="Y">Yes</option>
      <option value="N">No</option>
    </select>
  </div>
  <span class="inputError" id="customerNarrationReq_box"><%=siteValidation.getErrorMessage("customerNarration")%></span>
</div>

<div class="form-group ">
  <label class="floatinglabel"><sup class="text-red" id="asterisk"></sup> Customised Narration </label>
  <input type="text" class="form-control" name="customisedNarration" id="customisedNarration" onfocus="hideerrmsgdelayed('customisedNarration')" maxlength="50" />
  <span class="inputError" id="customisedNarration_box"><%=siteValidation.getErrorMessage("customisedNarration")%></span>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring Angular 8 HTTP Observables within the ngOnInit Lifecycle Hook

Currently, I am still a beginner in Angular and learning Angular 8. I am in the process of creating a simple API communication service to retrieve the necessary data for display. Within my main component, there is a sub-component that also needs to fetch ...

AngularJS - Establishing communication between controller and view

I am facing an issue with the Angularjs view. I seem to be making a mistake somewhere and I can't figure out where the problem lies. I hope someone can assist me with this. The problem is that {{user.login}} (userRepoInfo.html file) is not being call ...

What steps should I take to make jQuery compatible with a Greasemonkey 0.8 script on Firefox 2, without internet access on the computer?

Currently using Firefox 2.0.0.11, Greasemonkey 0.8.x, and the latest version of jQuery (1.3.2) that is compatible with Greasemonkey 0.8. Attempting to load this Userscript: // ==UserScript== // @name TEST // @include * // @require jquery. ...

What is the best way to change the height of a div element as the user scrolls using JavaScript exclusively?

Coding with JavaScript var changeHeight = () => { let flag = 0; while(flag != 1) { size += 1; return size; } if(size == window.innerHeight/2){ flag == 1; } } var size = 5; document.body.style.height = &qu ...

Tips for adjusting the size of grid tiles according to the dimensions of the window within a specific range

I am currently exploring how to replicate the effect found on this webpage: When the window size is adjusted, javascript dynamically resizes the grid tiles between 200 and 240px based on the optimal fit for the screen. Is there a ready-made JavaScript/jQ ...

Having difficulty linking several checkbox options

I'm currently using the following code to cascade my checkbox list items. The issue I'm facing is that when I select one checkbox, cascading works fine, but when I select multiple checkboxes, cascading doesn't work. Could the problem be rela ...

Clicking on Fixed Positioning triggers a reset

When I activate the sidebar by clicking the menu button, it remains fixed in position until the first scroll. However, if I interact with the sidebar by clicking on it, the button resets and goes back to the top of the page. This issue seems to only occur ...

transform a JSON object into a targeted JSON array

Looking to transform a JSON object into an array format, like so: [ { "name": "Batting" ,"data": [10,20,30,40]} , { "name": "Bowling" ,"data": [10,30,50,70] },{ "name": "Fielding" ,"data": [20,40,50,70]}] While I can create JSON objects for each index, I ...

What is the best way to obtain a distinct collection from two arrays that eliminates the second appearance of an element based on a key's value, rather than the first as in the Lodash uniqueBy function?

Let's say I have two arrays... const arr1 = [ { id: 1: newBid: true } ]; const arr2 = [ { id: 1, newBid: false }, { id: 2, newBid: false } ]; My goal is to end up with an array that looks like this [ { id: 1, newBid: false }, { id: 2, newBid: fals ...

State is not currently utilizing the variable

const DonorsTables = () =>{ const [search, setSearch] = useState(""); const [countries, setCountries] = useState([]); const [filteredcountries, setFilteredCountries] = useState([]); const getCountries = async () => { try { ...

When using $resource.save, it returns a "Resource" instead of just an ID

For some reason, I am struggling with a seemingly simple task and cannot find a solution by going through documentation or other Angular related questions on SO. I may not be the brightest, so I could really use some help here as I am feeling stuck. Take ...

Issue with handling multiple messages in WebSocket responses as Promises

In my web project using angularjs, I have the task of downloading data every second via a WebSocket. However, I encounter issues with handling multiple requests of different types. Although I utilize Promises to structure the requests, sometimes the respon ...

Creating a regular expression to match special characters using JavaScript

I'm making an attempt to verify certain characters in my code. If the input field contains specific characters for each character, it will return true; otherwise, it will return false. function isChar(value) { //Creating a regex pattern to permit ...

Saving the current $index from an ng-repeat loop to a database row (with row numbers 1.1, 1.2, 1.3) using AngularJS

Currently, I am developing the index page functionality for a book. i.e : 1.1 1.1.1 1.2 1.2.1 In this setup, 1.1 and 1.2 are the parent ng-repeats, while 1.1.1 and 1.2.1 are the child ng-repeats. My goal is to store these numbers ( ...

Achieving enlightenment with Satori in NextJS: Transforming SVG to PNG in a NodeJS Environment

I am currently exploring the capabilities of satori and integrating it into my next.js api routes. (I'm unable to utilize the vercel/og package). While I have successfully set everything up, I'm facing a challenge in converting the svg image gen ...

Crafting callback functions

My jQuery code looks like this: $('#current_image').fadeOut(function(){ $('#current_image').attr('src',newImage).show(); }); This process is wonderful - the nested function runs smoothly after the fadeOut. I ...

Struggling to combine select dropdown choices in one calculation

​​I'm currently working on a project where I need to create a website that multiplies three numbers selected from dropdown menus together. However, when I attempt to perform the calculation, I only get the result "1" displayed. I've spent sev ...

Is the MVC pattern adhered to by ExpressJS?

Currently, I am diving into the world of creating an MVC Website With ExpressJS using resources from I'm curious to know if ExpressJS strictly adheres to the MVC pattern, or if it follows a different approach like Flask which focuses more on the "C" ...

Combining Angular 2.0 within Angular 1.x: Elevating your module

Currently, I am attempting to incorporate an Angular 2.0 component within an Angular 1.x application (for experimentation and learning purposes). Upon further examination, I have observed that this can be achieved by referencing the Angular2 upgrade modul ...

Is setting cache: 'no-store' in a fetch request enough to mimic client-side rendering behavior in Next.js?

Currently, I am working with Next.js and utilizing the fetch method to retrieve data: const res = await fetch(`${process.env.url}/test`, { cache: 'no-store', }) My understanding is that specifying cache: 'no-store' will trigger a fre ...