unique jquery plugin accesses function from external javascript file

As a beginner, I am attempting to create a custom jQuery plugin for which I have a simple HTML form:

<form id="registerForm" action = "somepage" method="post" class="mb-sm">
    <div class="form-group">
        <div class="col-md-12">
            <label class="control-label" for="fname">First Name* :</label> 
            <input type="text" class="form-control" id="fname" placeholder="Enter Owner's First Name" name="fname">
            <div class="alert alert-danger hidden mt-lg" id="fnameerrbox"></div>
        </div>
    </div>
</form>

In the "js" folder, there is a javascript page named validation.js with the following code:

"use strict";
var errcontent;
function showerror(errbox, errcontent){
    if($(errbox).hasClass("hidden")){
    $(errbox).removeClass("hidden");
        $(errbox).html(errcontent);
    }
}
function hideerror(errbox, errcontent){
    if(!$(errbox).hasClass("hidden")){
    $(errbox).html(errcontent);
        $(errbox).addClass("hidden");
    }
}
(function ($){
$.fn.alphaNumeric = function(element, errbox){
var alphanumeric = /^[a-zA-Z 0-9.,]*$/;
    if(!alphanumeric.test(element)){
        errcontent = "Only alphabets, numbers, dot, comma are allowed";
        showerror(errbox, errcontent);
    }
    if(alphanumeric.test(element)){
        errcontent = "";
        hideerror(errbox, errcontent);
    }
}
})(jQuery);

Another javascript page named custom.js extracts values from input elements, here is the code:

"use strict";
var fname;
var errbox;

$(document).ready(function(){
    $("#fname").keyup(function(){
        fname = $('#fname').val();
        errbox = $("#fnameerrbox");
        alphaNumeric(fname, errbox); // This line is causing an error
    });
});

Upon running this, an error occurs:

Uncaught ReferenceError: alphaNumeric is not defined at HTMLInputElement. (custom.js:8) at HTMLInputElement.dispatch (jquery.min.js:2) at HTMLInputElement.y.handle (jquery.min.js:2)

I understand that I need to initialize this and my validation method "alphaNumeric" is not defined, but I am unsure of how to do so. Being new to this, I would greatly appreciate any assistance. Thank you.

Answer №1

Utilizing $.fn.myFunc is essential when you intend to perform tasks like $('#my-element').myFunc(), where the element gets passed under this within myFunc. In this particular scenario, creating a jQuery plugin may not be necessary as you are working with a string rather than a DOM element. However, you can simplify things by eliminating the .fn part:

$.alphaNumeric = function(inputElement, errorBox){
var alphaNumericPattern = /^[a-zA-Z 0-9.,]*$/;
    if(!alphaNumericPattern.test(inputElement)){
        errorMessage = "Only alphabets, numbers, dot, and comma are allowed";
        showError(errorBox, errorMessage);
    }
    if(alphaNumericPattern.test(inputElement)){
        errorMessage = "";
        hideError(errorBox, errorMessage);
    }
}

Additionally, in your document ready section:

$(document).ready(function(){
    $("#fname").keyup(function(){
        var enteredName = $('#fname').val();
        var displayError = $("#fnameerrbox");
        $.alphaNumeric(enteredName, displayError);
    });
});

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

Avoid displaying null values in SELECT and GET operations when using node-postgres

Within my Express API functionality, I aim to offer the client flexibility in providing their contact details, namely phone number or website address, with the option of leaving them blank. The SELECT queries in use are as follows: -- Retrieve all users S ...

How can the onclick attribute be modified in an HTML document?

I am looking to update the data-pro-bar-percent attribute of a progress bar from 80 to 100 when a specific link is clicked. The change in attribute needs to be as follows: data-pro-bar-percent="80" --> data-pro-bar-percent="100" This is the current HTML ...

I am having trouble figuring out the issue with the state and how to properly implement it in Typescript

I am having difficulties sending emails using Nodemailer, TypeScript, and NextJS. The contact.tsx file within the state component is causing errors when using setform. As a beginner in TypeScript, I have been unable to find a solution to this issue. Any he ...

Display Numerous Values Using Ajax

Having difficulty showing data from the 'deskripsisrt' table in a modal bootstrap? I have successfully displayed from the 'srtptr' table, but not sure how to proceed with the 'deskripsisrt' table. Here's a snippet from my ...

The session expiration feature is malfunctioning

My web application has a session timeout of 30 minutes, but users are reporting that the sessions are not timing out correctly. It seems that on the client side, an automated AJAX request is being sent to the server every 30 seconds to retrieve data. Cou ...

Enhancing Form Fields Dynamically using AJAX and JSON

I'm trying to update specific fields in my form after fetching data from a database using AJAX and JSON. Here is the code snippet: In my form: <div class="form"> <?php $form=$this->beginWidget('CActiveForm', array( ' ...

Hovering over the designated area will reveal the appearance of

I've encountered an issue with a list group in a card. Specifically, when hovering over the topmost item in the list group, a border appears underneath it (which should only appear when hovering). However, when I try to override this behavior using :h ...

The ng-controller directive fails to function on the content of Kendo tabstrip tabs

My ng-controller is not functioning properly for the kendo tabstrip tab content. Could you please review my code below? <!--tabstripCtrl.js--> angular.module('tabstripApp',[]); var app = angular.module('tabstripApp'); app.con ...

Excessive Function Calls Detected in AngularJS Application

I'm facing a major performance issue. I need to display details in a list, but the function is being called excessively. Feel free to check out the demo here Here's the HTML code snippet : <div ng-controller="MyCtrl as ctrl"> <p>K ...

Tips for automatically scrolling mat-select option to the top when mat-select is closed

Is there a way to automatically scroll the mat-select options to the top after closing it? I am faced with a situation where I have numerous options in my mat-select dropdown. If I select an option from the bottom and then close the mat-select, is there a ...

Setting a background image as a variable in Vue.js

I am currently working on a vue.js component that includes a div.icon: Vue.component('obj', { props: ['img', 'name'], template: '<div><div class="icon"></div> {{ name }}</div>' }) While ...

Utilizing Vue JS for filtering numerical data

When I search for letters, my code below works well. However, when it comes to numbers like flat_number, it gives me an error saying flat.flat_number.toLowerCase is not a function filteredList() { return this.Flats.filter((flat) => { return ( ...

Unable to call Success function in JQuery AJAX request

Here is a simple JQuery ajax request I am working on: $.ajax("../ajax/data/items.json", { success: setContent, type: "GET", dataType: "json" }); function setContent(data, status, jqxhr) { alert("Hello!"); } The json file loads successfully with a 200 r ...

What is the method for displaying script commands within package.json files?

With a multitude of repositories, each one unique in its setup, I find myself constantly referencing the package.json file to double-check the scripts. "scripts": { "start": "npm run dev" "build:dev": "N ...

Guide to stacking blocks on top of each other

How can I create even spacing between blocks of different heights? For instance, in the image below, you can see that block 2 should be positioned directly under block 1. https://i.stack.imgur.com/RnYbP.png https://i.stack.imgur.com/LHvlz.png ...

How can I prevent buttons from being created using ngFor in Angular?

I need help with creating an HTML table that includes a cell with a button and a dropdown generated using ngFor. How can I disable the buttons (generated via ngFor) if no value is selected from the dropdown? Here's what I have tried so far: In my App ...

Transfer data to server using AJAX POST method including uploading file and sending textbox information

I am facing an issue with uploading an image file in my HTML form. I can successfully enter text fields and see the values in the database, but when it comes to uploading the image file using Ajax technique and HTTP POST request, I encounter a problem. My ...

Is it advisable to load 10,000 rows into memory within my Angular application?

Currently, I am in the process of creating a customer management tool using Angular.js that will allow me to directly load 10,000 customers into the $scope. This enables me to efficiently search for specific data and manipulate it without the need for serv ...

Create a functionality wherein a checkbox becomes visible after submission by implementing ajax

My form is set up to record the attendance of staff members. Once the form is submitted via ajax, I want the checkboxes corresponding to the selected staff members to be automatically checked. The code below shows how the attendance information for all sta ...

Deletion of ::before and ::after pseudo-elements upon addition of the class is-sticky

One issue I'm facing is that when the class is-sticky is applied to my menu, the ::before and ::after pseudo-elements on my logo become unnecessary. As I am not very proficient in JQuery, I have been unable to resolve this by searching online. The HT ...