The process of defining properties of an input element using the defineObject JavaScript method

How do I define properties like placeholder or pattern using the following code:

Object.defineProperty(inputProto, 'placeholder', {value: 20, writable: true});

Although it works, when I check on the HTML, it shows as undefined.

Is there a way to define a property for a Web Component in JavaScript without explicitly setting it in the HTML?

Code Snippet:

var inputProto = Object.create(HTMLInputElement.prototype);
//JS API functions (component prototype)   
inputProto.onClear = function() {
    this.value = "";
    this.style.position = "static";
    this.placeholder = "New Text";
}

inputProto.setPos = function(x, y) {
    this.style.top = x + "px";
    this.style.left = y + "px";
    this.style.position = "relative";
}

inputProto.setDimensions = function(width, height) {
    this.style.width = width + "px";
    this.style.height = height + "px";
}

inputProto.caps = function(input) {
    input = this.value;
    var regEx = /[A-Z]/;
    var match = regEx.test(input);
    if (match) {
        alert("Valid")
    } else {
        alert("Not valid")
    }
}

inputProto.lowerCaps = function(input) {
    input = this.value;
    var regEx = /[^A-Z]/;
    var match = regEx.test(input);
    if (match) {
        alert("Valid")
    } else {
        alert("Not valid")
    }
}

var EgComponent = document.registerElement('eg-input', {
    prototype: inputProto,
    extends: 'input'
});

var egcomp = new EgComponent();
//existing component function in the DOM
function test() {
    egcomp.onClear();
    egcomp.setDimensions(250, 15);
}

function test1() {
    egcomp.setDimensions(350, 15);
}

function test2() {
    egcomp.caps();
}

function test3() {
    egcomp.lowerCaps();
}

function test4() {
    egcomp.setPos(30, 580);
}
//adding the component to the HTML from the DOM
document.body.appendChild(egcomp);

Answer №1

When using Object.defineProperty to set properties, the value ends up as undefined if you apply it to the prototype instead of an actual instance of EgComponent:

/* This is incorrect. */
Object.defineProperty(inputProto, "placeholder", {value: 20, writable: true});

Properties like value, pattern, and placeholder belong to instances, not prototypes. To correctly assign these properties to an instance of EgComponent, you should utilize defineProperty on egcomp rather than inputProto:

/* This is the correct way to set the property. */
Object.defineProperty(egcomp, "placeholder", {value: 20, writable: true});

By setting the property in this manner, you can access the value of 20 with egcomp.placeholder; in the console. However, although the placeholder property for egcomp is updated, the corresponding HTML attribute remains unchanged. To address this, skip Object.defineProperty and opt for the traditional approach:

/* Here's how you should set the property and HTML attribute. */
egcomp.placeholder = 20;

Observe the provided snippet to observe this functionality.

Snippet:

/* ---------- The EgComponent class ---------- */
;(function () {
  /* Establish a new object originating from the prototype of HTMLInputElement. */
  var inputProto = Object.create(HTMLInputElement.prototype);

  /* Specify fundamental methods for the component's prototype */
  Object.defineProperties(inputProto, {
    /* Method for clearing a component instance. */
    onClear: {
      value: function() {
        this.value = "";
        this.style.position = "static";
        this.placeholder = "New Text";
      }
    },

    /* Method for positioning a component instance. */
    setPos: {
      value: function(x, y) {
        this.style.top = x + "px";
        this.style.left = y + "px";
        this.style.position = "relative";
      }
    },

    /* Method for setting dimensions of a component instance. */
    setDimensions: {
      value: function(width, height) {
        this.style.width = width + "px";
        this.style.height = height + "px";
      }
    },

    /* Determine if the value of a component instance is uppercase. */
    caps: {
      value: function(input) {
        alert(/[A-Z]/.test(this.value) ? "Valid" : "Not Valid");
      }
    },

    /* Determine if the value of a component instance is lowercase. */
    lowerCaps: {
      value: function(input) {
        alert(/[a-z]/.test(this.value) ? "Valid" : "Not Valid");
      }
    },
  });

  /* Enlist the EgComponent within the browser. */
  window.EgComponent = document.registerElement("eg-input", {
    prototype: inputProto,
    extends: "input"
  });
})();



/* ---------- Instantiating an EgComponent ---------- */

/* Generate a fresh EgComponent instance. */
var egcomp = new EgComponent();

/* Assign the 'placeholder' property. */
egcomp.placeholder = 20;

/* Define the 'pattern' property. */
egcomp.pattern = /[a-z]/;

/* Embed the component into the document body. */
document.body.appendChild(egcomp);

/* Output the component to the console. */
console.log(egcomp);

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

Establishing a connection between JavaScript and MySQL within an HTML document

Recently, I started using node.js's node-mysql driver for MySQL and decided to write this piece of code: var mysql = require("mysql"); var connection = mysql.createConnection({ host : "localhost", user : "root", ...

Unable to use jQuery ajax functionality without a page refresh

The previous year and current year are both set to 0. Similarly, the previous month and current month are also initialized to 0. A boolean variable $ul_open is declared and set to false. We retrieve a list of posts using get_posts with specified paramet ...

What could be causing the Angular compile error to occur in this straightforward component?

I have just created this small Angular 4 module: import { BrowserModule } from "@angular/platform-browser"; import { NgModule } from "@angular/core"; import { FormsModule } from "@angular/forms"; import { HttpModule } from "@angular/http"; import { Foote ...

Creating a Blog Post with Pagination on Blogger

After creating pagination for 1 to 10 posts, I encountered an issue where clicking on page 1 or 2 does not show as the visited or active page. Any advice on how to fix this? Below is the CSS code: .post-pagination { margin: 100px auto; text-align ...

Vue component fails to trigger upon receiving the 'mouseleave' event

I am currently working on a navbar with dynamic component navigation, where hovering over a navbar-link should display the corresponding component and hiding it when the mouse leaves. Although the components are displayed correctly upon hover, they do not ...

Learning how to toggle default snippet keywords on and off based on specific scenarios within the Angular Ace Editor

Within the Ace editor, I have incorporated custom snippets alongside the default ones. However, there are certain scenarios where I would like to exclusively display the custom snippets and hide the default ones. Is there a way to disable or conceal the ...

Tips for globally overriding MUIv4 class in JSS for nested themes

Summary: Skip to EDIT2 MUIv4 has generated the following classes for me based on my nested theming: <label class="MuiFormLabel-root-121 MuiInputLabel-root-113 MuiInputLabel-formControl-115 MuiInputLabel-animated-118 MuiInputLabel-shrink-117 M ...

Previewing an uploaded image before submitting with FileBase64: A step-by-step guide

How can I implement a preview for an uploaded image before submitting the form? I have the upload functionality working but I would like to add a preview feature for the image. Below is the code snippet I am currently using: const [shop, setShop] = us ...

Real-time functionality is not supported by Firebase functions

I've set up a firebase query within a method in VueJS: data: {this.todaysEvents}, methods : { getTodaysEvents (day) { this.todaysEvents = [] const events = db.ref('calendar') const query = events.orderByChild('da ...

Generate a spreadsheet file in xlsx format by using the exceljs library in Node

I am currently working with exceljs 3.8 in an attempt to generate a new XLSX file, but unfortunately the code below seems to be malfunctioning. createNewExcelFile: function (excelFilePath) { //excelFilePath: Path and filename for the Exce ...

The Google Charts chartRangeFilter displays incorrectly upon reducing the height to a specific, seemingly random level

I am relatively new to web coding and currently working on a dashboard project for my client. I am using Google Charts to display the water level data that I collect. My issue is with the chartRangeFilter control - it works fine when the height is large en ...

Leveraging NextJS14 Static Site Generation (SSG) for seamless Authentication with Clerk

Having a bit of trouble with Next.js Static Site Generation (SSG) and protected routes. SSG requires data to be available at build time, while protected routes need user authentication which isn't possible during this phase. The pages I'm trying ...

Encountering the issue "Error: Uncaught PDOException - SQLSTATE[42000] - Syntax error or access violation: 1064"

I encountered an error that says: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064. It seems to be a syntax error in my SQL statement. Can you help me figure out what's wrong with it? require_once "dbconnect.inc.php"; $e ...

What is the best way to dynamically load a personalized JavaScript file for individual users depending on their PHP login credentials?

Currently, I am conducting a web-based experiment in which students log into a website to take practice tests for a class. Initially, the students land on a login page that includes the following code: include_once("core/config.php"); include_once("core/ ...

Executing Code Upon Module Load and Presenting It as Middleware

I am currently delving into the intricacies of how exporting and importing modules function in Nodejs. One of my tasks involves using a specific file to seed a mongodb database. Surprisingly, this file operates flawlessly and delivers the desired results ...

Customize the focus function for an individual element

I am working on a custom component that needs to seamlessly integrate with the native blur and focus functions. My goal is to override these functions in order to achieve the specific functionality I need. Currently, I have managed to override the prototy ...

Utilize the Jest moduleNameMapper for locating files: "resolver": undefined

Among the various files I have, there is a text file located in the component directory within the path: src/components/text Despite this, Jest is unable to locate the file when utilizing the webpack alias import Text from "components/text"; I ...

Retrieve events triggered by each element

Currently, my research centers around digital marketing and user experience. In order to gather the necessary data for this study, I must collect event logs from all components within a UI to create datasets on usability patterns. In a web interface, such ...

Python 3 Selenium struggles to run JavaScript code

I'm currently working with Python 3 and utilizing Selenium to extract data from a website. I am attempting to eliminate a specific class from a list item in order to successfully display the desired information. Here is the code snippet in question: ...

Using AngularJS to trigger a factory function from an HTML element with the ng-click directive

Need help with calling a function called myfunc, which is defined in Factory, from an HTML file: <button type="button" class="btn btn-default btn-sm" ng-click="myfunc(search_name)">Search</button> Here is the code for the controller and facto ...