Obtain the control ID within a JavaScript function by passing it as a parameter

Hello everyone, I'm a bit rusty with my JS skills but I'm trying to tackle creating some functions that will work on the client side rather than relying on server code. Here's what I'm attempting to achieve:

I have a dropdown control and a textbox. The textbox is initially disabled and its state is dependent on the value selected from the dropdown.

My goal is to trigger a function that will enable the textbox for text entry when "YES" is selected from the dropdown. Here is the code snippet I am working with:

function DependentControlByDropDown(sender, Control, DependentControlID) {
    try {

       var senderControl = sender.selectedOptions[0].text;
       var controlEnable = (senderControl == Control);
       console.log(controlEnable);

       var control = document.getElementById(DependentControlID); // This returns NULL when I do console.log(control)
       DependentControlID.disabled = controlEnable; // controlEnable has a value of either TRUE or FALSE, but it doesn't affect DependentControlID
       }
   catch (e) {
        alert("DependentControlByDropDown : " + e.message);
   }
  }

I'm invoking this function in the dropdown like this:

onchange="DependentControlByDropDown(this,'Yes','txtbox1')"

When testing, I can see that I'm getting the correct value 'Yes' or 'No'. However, the issue lies with the dependent control. Even though console.log(DependentControlID) shows me the correct control, setting disabled=false does not work. I also tried

document.getElementByID(DependentControlID).disabled=false
, yet that did not solve the problem either. Any suggestions?

Answer №1

After some discussion in the comments of your post, it appears that you are utilizing ASP.NET.

This detail is crucial to acknowledge because ASP.NET automatically changes assigned IDs to guarantee uniqueness. For instance, if you were to use...

<asp:Textbox runat="server" id="txtbox1"></asp:Textbox>

...the resulting HTML might resemble something like this (for illustration purposes)...

<input id="ctl00$MainContent$txtbox1">

Due to this behavior, getElementById("txtbox1") will not locate anything.


To prevent this issue, you can include ClientIdMode="static" to your textbox:

<asp:Textbox runat="server" ClientIdMode="static" id="txtbox1"></asp:Textbox>

The resulting HTML will now be as follows...

<input id="txtbox1">

NOTE: In case there are multiple textboxes on the page, such as when using them within a GridView or a Repeater, avoid utilizing ClientIdMode="static"! This will generate duplicate IDs, which are not permissible.

Answer №2

The issue at hand is your attempt to access the textbox using its ID as text. You should instead set the disabled attribute on its node value, which you have already done with the control.

Moreover, you were setting the disabled attribute of the textbox to the same value as controlEnable. I went ahead and changed it to the OPPOSITE of controlEnable


function DependentControlByDropDown(sender, Control, DependentControlID) {
  try {
var senderControl = sender.selectedOptions[0].text;
var controlEnable = (senderControl == Control);

console.log('controlEnable',controlEnable);
console.log('DependentControlID', DependentControlID);

var control = document.getElementById(DependentControlID);
console.log('control', control);

control.disabled = !controlEnable;
  } catch (e) {
alert("DependentControlByDropDown : " + e.message);
  }
}
<input id="txtbox1" />
<select onchange="DependentControlByDropDown(this,'Yes','txtbox1')">
  <option value=""></option>
  <option value="Yes">Yes</option>
  <option value="No">No</option>
</select>

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

Possible undefined object in React Redux

I'm encountering a Typescript issue where Redux object I am utilizing is potentially undefined, even though I have not specified its type as potentially being undefined or set it to be undefined anywhere in my code. /redux/globalSettings/actions.ts ...

The React date picker is experiencing a delay when opened with a click

A peculiar problem has arisen with react-datepicker. I have successfully integrated my datepicker with Redux Form, and the code is as follows: <DatePicker customInput={<CustomDateInputNew {...props} />} onChange={date => { props.input. ...

Switch out a visual element for Dropzone.js

During my recent project, I utilized Dropzone.js for image uploads. However, I am now interested in transforming the dropzone area into an actual image. For instance, if there is a "featured image" attached to an article, users should be able to drag and ...

How to change a string into an object in JavaScript that includes a colon symbol

Can anyone suggest the most efficient way to convert the string var xx = "website:https://google.com"; into a dictionary format like {website:"https://google.com"}? Usually, I use str.split(":"), but in this case, there are multiple colons. Would using t ...

Divide the string into two halves and display them in separate div elements

I am in need of a code that can split a string in half. For instance, if the inputted name is "Trishy", which consists of 6 letters, the first 3 letters should be placed into the second li within the <ul class="hardcover_front">, while the remaining ...

Transferring SQL-generated JSON object from PHP to JavaScript

Seeking assistance with passing a JSON object from PHP to Javascript. The object is populated from an SQL Database using the following PHP code snippet. <?php $conn = mysql_connect("localhost","root",""); if(! $conn ) { die('C ...

"Error: Multer is Unable to Read the Undefined File

Despite my best efforts, I am unable to get multer's file upload feature to work. Despite studying numerous tutorials and guides on YouTube, as well as diving into countless StackOverflow threads, I still struggle to make it function properly through ...

Activate live streaming on Youtube's API

Utilizing the Youtube API, I have successfully created events from my application in Youtube for Live streaming as demonstrated by the provided code. However, I have specific requirements: 1) Is it possible to initiate live streaming from my application i ...

Utilizing vue-router to create two separate navigation bars where only one link is highlighted as active

In my setup, I have implemented two sections with navigation structured as follows: <ul class="navigation-list"> <li v-for="(route, index) in navRoutes"> <router-link :to="route.path"> <span>{{ route.name }}</span> ...

express.js - Issue with session access middleware

I am currently working on a middleware using JavaScript, Express, and Session to restrict access to specific pages based on the existence of a session. Here is my attempt: function checkAdminCredentials(req, res, next) { if (req.session.adminId) { n ...

Enter key not activating keycode trigger as expected

Trying to utilize the keycode to activate a button click on enter key press. The current code functions properly when an alert is inserted in the keycode function, but does not work as intended when placed inside the .click(function.... Unsure of the missi ...

iterate through all the items in the radioButton collection

Hello, I am looking to iterate through this object and display checkbox values along with their indices. data: [ { key1: 'last 6 months' }, { key2: 'last 30 days' } ] I would like to creat ...

Organizing Files and Creating Applications with Electron

Recently, I came across Electron and found it to be a fantastic tool for developing desktop applications. I created a basic Twitter Aggregator that functions when I execute nodemon app.js. Now, I want to package it with Atom in order to run it in its own w ...

How can we toggle a function to expand or collapse fields generated in an ngFor loop?

One of my challenges involves managing a div that is repeated using *ngFor in Angular. This results in multiple divs on the page, each containing collapsible fields that can toggle. Essentially, I have nested collapsible fields within other collapsible fie ...

Can you help me troubleshoot an issue I am facing with the expand table in Angular 9 and JS? I am getting an

Here you can find the code demonstration and behavior: No extensive explanation is necessary. Check out the StackBlitz demo by clicking on the first row to view its details. Then, click on the second row to see how the details from the first row are repl ...

How can we access state data in a Vuex component once it is mounted?

My goal is to initialize a Quill.js editor instance in a Vue component once it is loaded using the mounted() hook. However, I am facing an issue where I need to set the Quill's content using Quill.setContents() within the same mounted() hook with data ...

Babel exclusively processes JavaScript files in my Vue project, rather than the project as a whole

I need to make my Vue project compatible with an old iPad running iOS/safari version 5, which requires transpiling it to ES5 using Babel. Here is the content of my babel.config.js: presets: [ //'@vue/cli-plugin-babel/preset', ["@babel/ ...

Tips for automatically closing SweetAlert after an AJAX request finishes

I recently implemented Sweet-alert into my Angular project. function RetrieveDataFromAPI(url) { SweetAlert.swal( { title: "", text: "Please wait.", imageUrl: "../../app/app-img/loading_spinner.gif", showConfirmB ...

CSS personalized by the user

I want to develop an application that allows users to input their customized CSS, which will then be implemented on the webpage. Is there a straightforward method to achieve this, or do I need to manually parse and modify the CSS by accessing elements like ...

Tips for retrieving the HTML file of a modified canvas in HTML5

I’m currently working on a project to develop a website that allows users to design their own pages by simply dragging and dropping elements onto the canvas. The goal is for users to be able to save their creations as an HTML file. I’m facing challen ...