The optimal method for assigning a value to a field in Javascript without having prior knowledge of whether it will be an input, select, textarea, radio, or checkbox field

I am currently working on a project that involves enhancing a tool which enables users to create forms and add various fields to it. Some of these fields are predefined (such as State, Province) and have specific targetable names and classes that are consistent across all forms (e.g. id='region'). However, the format of each field (Input, Textarea, Select, Checkbox, or Radio) can be chosen by the user when adding them to their form. It is crucial for us to be able to update the value of a targeted field (e.g. id="region") without prior knowledge of its input type.

We initially thought that there might be a simple vanilla JavaScript solution available on NPM, but our search did not yield any results. Perhaps we overlooked something?

In the end, we devised the following solution in TypeScript, but we wanted to explore if there are any other existing solutions out there. We would prefer not to reinvent the wheel if someone has already tackled this issue before.

// Set a value to any field. If it's a dropdown, radio, or checkbox, it selects the proper option matching the value
setFieldValue(name: string, value: unknown) {
    (document.getElementsByName(name) as NodeListOf<HTMLFormElement>).forEach((field) => {
        if ('type' in field) {
            switch (field.type) {
                case 'select-one':
                case 'select-multiple':
                    for (const option of field.options) {
                        if (option.value == value) {
                            option.selected = true;
                        }
                    }
                    break;
                case 'checkbox':
                case 'radio':
                    // @TODO: Try to trigger the onChange event
                    if (field.value == value) {
                        field.checked = true;
                    }
                    break;
                case 'textarea':
                case 'text':
                default:
                    field.value = value;
            }
        }
    })
    return;
}

Answer №1

For those using ASP.NET WebForms, a highly effective Javascript library to consider is Alpine.js. This powerful tool allows you to easily bind input controls to a model, streamlining the process of working with your data without needing to navigate through the DOM for controls.

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

Executing a JavaScript function from the code-behind

I have implemented a JavaScript function in an ASP.NET page. Here is the code in the ASP.NET Page: <HTML> <HEAD> <script type="text/javascript"> function Myfunction(){ document.getElementId('MyText').value ...

Issue with capturing events in Angular through emitting events

Apologies for my inexperience with Angular (V12), if I am not explaining my issue clearly. I am facing a problem with the $Event not capturing the custom object data emitted from another component. Upon setting up the function in the parent component, I en ...

Encountering an issue with my code in CodeIgniter

I encountered an error when trying to make an AJAX request in CodeIgniter, unlike the usual process in core PHP where we specify the file URL containing the query. The error I received was net::ERR_SSL_PROTOCOL_ERROR . Here is the JavaScript AJAX code sni ...

What could be the reason my script fails to execute during an AJAX refresh?

As I was working on my project's avatar uploader, everything seemed to be going smoothly until this morning when chaos ensued. It was a moment of pure sadness. Initially, selecting a file would prompt the crop tool to appear immediately, and it worke ...

Is it possible for me to return a function reference as a response to an API call?

Is it possible to return a function reference or function as a response to an API call from an Express server when using AngularJS as the front-end framework? I attempted to send the response object like this: {per: true, listEvnts: events} where events i ...

Troubleshooting a manual installation of the mysql2 package - encountering an

I've encountered an issue while trying to initialize Sequelize in my application. When using docker-compose to build and run the app, I am prompted to manually download the mysql2 package. Despite my attempts to download it using various methods like ...

Refresh the page twice using ajax/jQuery and setTimeout function

When it comes to Ajax, Java script or CSS, I must confess that I struggle a bit. So please bear with me as I ask for some assistance. I am currently working on a CMS wrapped in Jquery mobile and unable to use meta refresh methods. How can I adjust the code ...

Connect to content on the current page

I am facing an issue where the linked heading of a section on the same page is getting lost under the fixed navigation bar when scrolling down. This problem seems to only occur on desktop view as it works fine on mobile preview. Here is the code I am curre ...

Show or hide a specific element based on whether a certain radio button is selected or deselected

After successfully displaying an element on radio button selection, I encountered the issue of the selected element remaining visible when another radio button in the group is chosen. What aspect am I overlooking? Regarding hiding elements with vanilla Ja ...

Producing outcomes through a search field using AngularJS and the Bootstrap framework

I want to show search results in a navigation menu. HTML <input type="text" ng-model="result" min-length="2" typeahead="institution.id as institution.name for institution in institutions($viewValue)" style="display:block" placeholder="Search"> JS ...

How can I protect a text or script file from being accessed or downloaded by entering its URL directly into the browser address bar?

While working on my JSP file, I have incorporated some Java-script code but to safeguard it from being visible to clients, I decided to store it in a separate codescript.js file and load it using ajax like so: $.ajax({ cache: true, dataType: "script ...

I am interested in developing a JavaScript program that can calculate multiples of 0.10

I am looking to let users input values that are multiples of 0.10, such as - 0.10, 0.20, 0.30....1.00, 1.10, 1.20...1.90, and so on. When a user enters a value in the text box, I have been checking the following validation: amount % 0.10 == 0 Is this a ...

Closing a modal using the Enter key in Angular 6

I was able to replicate the issue on StackBlitz using minimal code. To reproduce: Step 1: Input a word in the text field and press Enter on the keyboard. Step 2: A modal will pop up. Step 3: Hit Enter again on the keyboard. During Step 2, I encou ...

I need to retrieve a date value within a function

When using the input type = date, I am trying to retrieve the selected date value in a function. Here is my code: <input style='display:none;' type='date' value='<?php echo date(Y-m-d);?>' name='date' id ...

"Facing an issue with my handleChange function not getting triggered in MaterialUI. Can anyone

Why isn't my handleChange function being invoked with the TextField component from Material UI? Even though I can input values in the text fields, the component's state is not updating. Here is the Auth component: const Auth = () => { cons ...

Check the Django form that was submitted in the view to ensure its

When handling a POST request in my view, I am expecting data that has been submitted through a Django form. This is how the Django form is structured: class SubmitForm(forms.Form): title = forms.CharField(max_length=100) comment = forms.CharField ...

Tips for assigning a Custom Formik Component's value to the Formik value

I'm currently integrating Formik into my form alongside Google Places auto-complete feature. My goal is to display the places auto-complete functionality as a custom component within the Formik field. form.js <Formik initialValues={location:" ...

Tips for directing focus to an element within React JS

I have successfully integrated an infinite scroll list in my demo application. When a row is clicked, the user is taken to the detail screen, and this functionality is working perfectly. **However, I am encountering an issue with focusing on the last sele ...

Updating Object Properties in Angular 6 without Explicitly Setting Them

In my editor, users can modify product details. To allow for resetting these edits, I store the initial product instance in ngOnInit as initialProduct. However, I've encountered a strange problem: When adding a new tag, the properties of initialProdu ...

Build an intricate nested array structure using the properties of an object

My data object is structured like this: "parameters": { "firstName": "Alexa", "lastName": "Simpson", "city": "London" } The task at hand involves implementing the followin ...