The function is not executing as expected, with no errors detected in the console log

I've been working on this function, but I'm having trouble getting it to run properly. None of my console.log messages are showing up in the console. This function is supposed to validate emails upon submission, but only for a specific domain.

function checkEmailValidity() {
  console.log('First message')

  var emailInput = document.querySelectorAll('t186__input');
  console.log('Input checked');
  var submitButton = document.querySelectorAll('t-submit');
  console.log('Submit button checked');
  submitButton.addEventListener('click', function(e) {
    e.preventDefault();
    console.log('Click event detected');

    if (emailInput.val().indexOf('@rbc.com') !== -1) {
      return true;
      console.log('Validation successful');
    } else {
      alert("You have entered an invalid email address");
      return false;
    }

  });

}
<div class="t186__wrapper">
  <div class="t186__blockinput">
    <input type="text" name="EMAIL" class="t186__input t-input js-tilda-rule" value="" placeholder="Your E-mail" data-tilda-rule="email" style="color:#000000; border:1px solid #000000;" />
  </div>
  <div class="t186__blockbutton">
    <button type="submit" class="t-submit" style="color:#ffffff;background-color:#000000;">Subscribe</button>
  </div>
</div>

Answer №1

There are several errors present here that have been corrected:

1/.

  1. There is no need for querySelectorAll
  2. The initialization code was wrapped in a function but never called.
  3. The querySelector was not using a . for the class modifier.

var formInput = document.querySelector('.t186__input');
console.log('input');
var formSubmit = document.querySelector('.t-submit');
console.log('submit');

formSubmit.addEventListener('click', function(e) {

  console.log('click');
  if (formInput.value.indexOf('@rbc.com') !== -1) {
    return true;
    console.log('hey2');
  } else {  
    e.preventDefault();
    alert("You have entered an invalid email address");
    return false;
  }


});
<div class="t186__wrapper">
  <div class="t186__blockinput">
    <input type="text" name="EMAIL" class="t186__input t-input js-tilda-rule " value="" placeholder="Your E-mail" data-tilda-rule="email" style="color:#000000; border:1px solid #000000; "> </div>
  <div class="t186__blockbutton">
    <button type="submit" class="t-submit" style="color:#ffffff;background-color:#000000;">Subscribe</button>
  </div>
</div>

Additionally, a further tidy up of the code:

document.addEventListener('click', function(e) {
  if (e.target.matches('.t-submit')) {
    let regEx = /@rbc.com/;
    if (regEx.test(document.querySelector('.t186__input').value) === false) {   
      e.preventDefault(); 
      e.stopPropagation();
      alert("You have entered an invalid email address");
      return false;
    }
  }
});
<div class="t186__wrapper">
  <div class="t186__blockinput">
    <input type="text" name="EMAIL" class="t186__input t-input js-tilda-rule " value="" placeholder="Your E-mail" data-tilda-rule="email" style="color:#000000; border:1px solid #000000; "> </div>
  <div class="t186__blockbutton">
    <button type="submit" class="t-submit" style="color:#ffffff;background-color:#000000;">Subscribe</button>
  </div>
</div>

Final touches include wrapping the code in a form and handling the submit event. It is assumed that there is a form element somewhere in the code :)

// In this example we need to wait for the DOM to be ready. 
document.addEventListener('DOMContentLoaded', () => {
  // Code in here will execute the the HTML is loaded and the DOM is ready for use.
  setUpFormListener('t_frmSubmit'); // <--- replace with your form class name
});

function setUpFormListener(frmClassName) {
  // In this demo, we bind directly to the form submit. (note we use form.[class] to ensure we only select the form
  document.querySelector(`form.${frmClassName}`)
    .addEventListener('submit', function(e) {
      let regEx = /@rbc.com/;
      if (regEx.test(document.querySelector('.t186__input').value) === false) {
        e.preventDefault();
        e.stopPropagation();
        alert("You have entered an invalid email address");
        return false;
      }
    });
}
<form class="t_frmSubmit" submit="_blank"> 

  <div class="t186__wrapper">
    <div class="t186__blockinput">
      <input type="text" name="EMAIL" class="t186__input t-input js-tilda-rule " value="" placeholder="Your E-mail" data-tilda-rule="email" style="color:#000000; border:1px solid #000000; "> </div>
    <div class="t186__blockbutton">
      <button type="submit" class="t-submit" style="color:#ffffff;background-color:#000000;">Subscribe</button>
    </div>
  </div>

</form>

Answer №2

querySelectorAll('t186__input') and querySelectorAll('t-submit') are specifically searching for elements with the tags <t186__input and <t-submit.

Based on the structure of your HTML, these tags are actually classes on the elements. Therefore, you should use a class selector to target them.

querySelectorAll('.t186__input') and querySelectorAll('.t-submit')

It's important to note that querySelectorAll returns an array of nodes, so you'll need to iterate through them to access each individual element.

If you're expecting only one element with that class, consider using querySelector instead.

Lastly, you've defined the function but you're not actually calling the emailvalid function anywhere in your code.

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

Repurposing JavaScript objects after clearing their contents

Here's my issue. I'm working with a Javascript object, initialized as var stack = {}. This object is used in my project to store arrays. When the user clicks the add button, an array is added to the object with a specific key that is inputted in ...

Selenium and Python: Dealing with the ElementNotInteractableException when trying to input a value in a td element

My attempt to input the number 1 into the MasterPack boxes in this table is met with an error indicating that it is not interactable. https://i.sstatic.net/J79p6.png I encountered the "element not interactable" error while using the following code: driver ...

Invoking a C++ dll in the renderer process of a Node.js application with Electron using node ffi

As I work on developing a windows application using electron, my goal is to utilize the ffi-napi to invoke C++ .dll methods. However, I am facing a challenge with the "Passing_Dll.js" file, where the label with id "GenName" is not being updated when clicki ...

Is there a way to bring in a variable from the front end script?

Is it possible to transfer an array of data from one HTML file to another? If so, how can this be done? Consider the following scenario: First HTML file <script> let tmp = <%- result %>; let a = '' for (const i in tmp){ ...

Unable to activate primary error handler in my Node.js Express application

I have implemented node express (4.15.2) and used the default error handler provided by the express generator function to manage errors. Here is the code snippet: const app = express(); app.set('port', config.enviroment.portNumber); app.use(log ...

Ways to expand a Bootstrap input field by clicking on it:

I have successfully created a search bar in my navbar, but I am looking to add functionality that allows the input field to expand to its normal size when clicked. I believe this will require some JavaScript implementation, however, I am unsure how to proc ...

The error message thrown in Node.js: "Cannot access 'filename' property of undefined object"

Struggling with an issue in nodejs, whenever I try to post with an image, I keep getting the error message "Cannot read property 'filename' of undefined" I've been trying to debug but can't find the root cause of the error. Can someone ...

having difficulty showing the column filter feature in the DataTable

I am currently utilizing a datatable and in need of an individual column-based search feature along with a global search. I am working with a 2D array. The search boxes are being displayed, however, the search functionality is not functioning correctly fo ...

"Troubleshooting: Next.js useEffect and useState hooks fail to function properly in a

Working on my project in nextjs, I've implemented the useEffect and useState hooks to fetch data: export default function PricingBlock({ data }) { const [pricingItems, setPricingItems] = useState() const [featuredItem, setFeaturedItem] = useState( ...

Getting js.map Files to Function Properly with UMD Modules

I am experiencing an issue with debugging TypeScript files in Chrome and Firefox. Specifically, when trying to debug the MapModuleTest.ts file, the debugger seems to be out of sync with the actual JavaScript code by two lines. This discrepancy makes settin ...

ngmodelchange activates when a mat-option is chosen in Angular Material

When a user initiates a search, an HTTP service is called to retrieve and display the response in a dropdown. The code below works well with this process. However, clicking on any option in the dropdown triggers the 'ngmodelchange' method to call ...

Syntax rules for JSON schema

I am interested in creating a validator for JSON files following the JSON schema paradigm. I have been searching for a grammar that outlines the JSON schema but haven't had any success. Is there a formal specification available for the JSON schema tha ...

Utilizing Kendo UI Jsonp in conjunction with a WordPress json plugin: A comprehensive

Issue at Hand: My goal is to modify a kendo UI data-binding example to work with my own jsonp request. Description of the Problem: Starting from a data-binding example here, I have created this jsfiddle that demonstrates the desired functionality. To a ...

Is it possible for the 'error' attribute to be deemed invalid or inappropriate within ajax?

I am encountering an issue with my mobile cordova application. When attempting to log in, I am facing the following error: Error: JavaScript runtime error - Object doesn't support property or method 'error' The error is being traced back t ...

Prevent a function from executing using ClearTimeout()

Looking for a way to control the progress of my progress bar using two buttons. Here's the code snippet: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0 /jquery.min.js"></scr ...

The unexpected token "[ ]" was encountered while assigning a numerical value to an array

Hey everyone, I have a question that's been bothering me and I can't seem to find the answer anywhere. I'm currently learning pure JavaScript and although I am familiar with several other programming languages, I keep running into an issue ...

What is the best way to retrieve a file using XMLHTTPRequest and Ajax?

I am currently using window.location.href to download a file, but this method requires a second call to my servlet which takes about 1 minute to generate the file. How can I download the file using XMLHTTPRequest instead? The solution should only work wi ...

Develop a precompiled library for Angular applications that utilizes Ahead-of-Time (AOT) compilation technology

My Angular 5 library is packaged for consumption by other apps in their node_modules. Currently, the app is compiled Just-in-Time(JIT) using rollup and gulp. I export it as a package, and developers use it in its JIT compiled form. After researching AOT ...

Ensure that the HTML input only accepts numbers and email addresses

Is there a way to restrict an HTML input field to only accept numbers and email IDs? <input id="input" type="text" /> ...

When using form.serialize() in Django forms, an empty object is being sent

Upon clicking the button, my AJAX request is sending an empty object Object { } instead of form data. The form on my page consists of checkboxes and its HTML structure is as follows: <form method="post" action="" data-id="filter-form"> //Included ...