Capturing and setting form element values within a Javascript Module Pattern

I'm looking to streamline my form element access using the Module pattern. The goal is to eliminate redundancy by organizing everything under a single module.

How can I achieve this without having to directly call the Anonymous function within the module itself?

For example, rather than writing: FormData.LastName(), I'd like to simplify it to: FormData.LastName;

Here's an attempt:

'use strict';

FormData = (function() {

    var formElement = document.forms.signup;

    return {

        LastName: function(){
            return formElement.lName.value;
        },

        SendBtn: function(){
            return formElement.submitSignupForm;
        }
    };

})();

The objective is to interact with the module and retrieve its internal values without resorting to Global or exposure.

FormData.SendBtn().addEventListener('click', function(e){

    document.getElementById('result').innerHTML = FormData.LastName();

    e.preventDefault();
}, false);

Another approach:

'use strict';

FormData = (function() {

    var formElement = document.forms.signup;

    var LName = function(input){

            return input.lName.value;
        };

    var SendBtn = function(input){

            return input.submitSignupForm;
        };

    return {

        LastName: LName(formElement),
        SendBtn:  SendBtn(formElement)
    };

})();

FormData.SendBtn.addEventListener('click', function(e){

    document.getElementById('result').innerHTML = FormData.LastName;

    e.preventDefault();

}, false);

Answer №1

Utilize Object.defineProperty Method

For instance: https://msdn.microsoft.com/en-us/library/dd548687%28v=vs.94%29.aspx
More comprehensive documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties

var Mod = (function(){
    var module, formElement;
    module = {};
    formElement = document.forms.signup;

    Object.defineProperty(module, 'LastName', {
        get: function () {
            return formElement.lName.value;
        },
        writable: false,
        enumerable: true,
        configurable: true
    });
    return module;
})();

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

Searching recursively for keys with empty values in an array using Javascript

I've written a function that recursively locates empty values in a nested array. The function initially produces the correct value, but it seems to reset it to the input value before returning the result. What could I be overlooking? Below is my co ...

What is the best way to transmit a two-dimensional array using ajax?

Here is the process I use to send data to the server: var points = []; var coords = polyline.geometry.getCoordinates(); for (var i = 0; i < coords.length; i++) { var x = (coords[i][0]).toFixed(4); var y = (coords[i][1]).toFixed(4); points[i ...

Sending back numerous information in the catch block

Recently, I was testing out the fetch API and encountered an issue with logging a fetch error. I tried catching the error and logging it within the catch block. Strangely, even when I added additional console.log statements in the catch block, they would ...

WebGl - Perspective skewing perspective

I've been working on implementing an oblique projection in WebGL, but I'm encountering an issue where the projection appears identical to ortho. Here's the snippet of code setting up the projection matrix: mat4.identityMatrix(pMatrix); ...

Utilize Vue to call a method by providing its name as a string

When designing a navbar, I encountered the need to include a list of buttons. Some of these buttons should act as links, while others should call specific methods. For example, clicking on "Home" should direct the user to /home and clicking on "Log out" sh ...

Different ways to resize an image in various sizes without relying on PHP thumb

I have developed an admin panel for managing reservations of charter, yacht and other vehicles. I am looking for a solution to upload only one image per vehicle and resize it in multiple sizes without relying on the phpthumb library due to its slow loadi ...

Mongoose: Enhancing Arrays with maximum values for each item

How to Update an Array Property in Mongoose with Item-Wise Max and Default Null Upon Instantiation I have a MongoDB collection that stores time series data in a fixed-length array (1 item per minute, 1 document per day). { 'series': '#1& ...

Attempting to navigate the world of AJAX and PHP

My experience with AJAX is limited, but I am currently working on a project that requires a form to submit data without refreshing the page. The goal is to display the result in a modal window instead. To achieve this functionality, I understand that imple ...

Retrieve information and auto-fill text boxes based on the selected dropdown menu option

UPDATED QUESTION STATUS I'm currently working with Laravel 5.7 and VueJs 2.5.*. However, I am facing a challenge where I need to automatically populate form textboxes with data from the database when a dropdown option is selected. Despite my efforts ...

Information sent to a slot does not trigger a response

Trying to create a mobile-friendly chat app, I want to hide the new message button during conversations and use a different button on desktop. In addition, I have a dialog for creating new chat groups. <v-dialog transition="dialog-top-transition&qu ...

I am seeking assistance with my code. It is passing most of the test cases, but is failing only two without any error messages. What could

I recently started teaching myself programming, so please excuse me if my question seems a bit basic. One of the challenges on CodeCamp requires defining a function that takes an array with 2 values as input and returns the Least Common Multiple (LCM) of ...

Obtain the content enclosed within parentheses using JavaScript

const str = "(c) (d)"; I need to separate the given string into an array The result should be [0] => 'c' [1] => 'd' ...

Accessing multi-dimensional array properties in PHP with JavaScript integration

In my PHP code, I have an array structured like this: <?php $data = array(); $data[0] = array('year' => 2001, 'month' => array( 'January' => array('val1' => 1000, 'v ...

Trying to bring in components from directories above

I'm currently facing an issue with importing components from a parent directory into my project. My goal is to be able to use these components across multiple projects, which seems like the most straightforward approach. However, when I attempt this, ...

Comparing Express.js View Engine to Manual Compilation

Currently, I am utilizing Express.js along with the hbs library to incorporate Handlebars templates in my application. Lately, I've delved into establishing a build system using gulp for my app and stumbled upon packages like gulp-handlebars. My query ...

Attempting to extract the class name of a tr tag but receiving a result of 'undefined'

I'm struggling to retrieve the class name from a specific <tr> tag. <table cellpadding=5 cellspacing=5> <tr id='cat_abc123' class='class_a'> <td>foo</td> <td><input type=& ...

What steps do I need to take to retrieve my paginated data from FaunaDB in a React frontend application?

I am facing a challenge when trying to access the data object that contains the keys (letter and extra) in my response from the faunadb database to the frontend react. Although I have used the map function in my frontend code, I have not been successful ...

How can I use JavaScript to disable a table row and then save the selected option in a MySQL database?

I have a PHP snippet that dynamically displays table rows. Each row contains a radio button with "Yes" and "No" options. I have implemented a JS function where, upon choosing an option, a pop-up box is displayed. If the user selects the "Yes" option in t ...

What is the best way to synchronize HTML5 audio playback on different browsers?

When working with audio files in different browsers like Chrome, Firefox, and Safari, I noticed that they seem to start at slightly different timestamps. This discrepancy becomes more pronounced as the audio progresses, with a gap of around 5 seconds after ...

Adjusting the size of the snap increments

When using gridstack, I have the ability to resize my widgets. However, I've noticed that when dragging on the widgets' handles, they snap to specific sizes, which seems to be a fixed amount. If I wanted to set the widget's size to something ...