What could be the reason for my button not activating my JavaScript function?

I am encountering an issue with my form-validation sample. When I click the submit button, it should display an alert message but it is not working as expected.

Here is a link to my sample: sample link

I would greatly appreciate any assistance in resolving this problem.

This is what I have attempted:

//button declaration

<button id="validateSubmit" [disabled]="reactForm.invalid" onclick="myFunction()" class="samplebtn e-control e-btn e-primary"
                            type="submit" style="height:40px;width: 150px;" data-ripple="true">Submit</button>
                            
//function for showing alert message
<script>
    function myFunction() {
        alert('your form is submitted');
    }
</script>

Answer №1

It is crucial to adhere to the code convention in computer programming. The indentation style serves as a guideline for organizing blocks of code and conveying program structure. Unlike some languages that use braces or keywords, languages like Python and occam rely on indentation to determine structure, known as the off-side rule.

If you introduce multi-space errors, it can lead to issues with attribute values such as your class value appearing as

samplebtn e-control e-btn e-primary"
                            type="submit" style="height:40px;width: 150px;" data-ripple="true">
.

This misconception can cause the error to think that Submit is another attribute of your button, resulting in confusion about how to handle the following <.

To prevent such errors, it is important to follow the convention outlined below for optimal functionality.

Same line convention

function myFunction() {
  alert('your form is submitted');
}
<button id="validateSubmit" [disabled]="reactForm.invalid" onclick="myFunction()" class="samplebtn e-control e-btn e-primary" type="submit" style="height:40px; width: 150px;" data-ripple="true">Submit</button>

Indentation convention

Alternatively, you can indent each attribute for better readability.

function myFunction() {
  alert('your form is submitted');
}
<button
  id="validateSubmit"
  [disabled]="reactForm.invalid"
  onclick="myFunction()"
  class="samplebtn e-control e-btn e-primary"
  type="submit"
  style="height:40px;width: 150px;"
  data-ripple="true">Submit</button>

Answer №2

It is recommended to utilize TypeScript for your action. If applicable, transfer your function to a TypeScript file instead of keeping it in the script. Check out this sample

If you wish to incorporate JavaScript in Angular, refer to this link

You can identify errors from the console window, which greatly aids in debugging.

export class ReactiveFormReactiveComponent implements OnInit {

reactForm: FormGroup;

constructor() {
  this.reactForm = new FormGroup({
    'check': new FormControl('required', [FormValidators.required]),
    'email_check': new FormControl('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="34475b59515b5a51745359555d581a575b59">[email protected]</a>', [FormValidators.email]),
    'url_check': new FormControl('www.anything.com', [FormValidators.url]),

  });
}

ngOnInit(): void {

}

get check() { return this.reactForm.get('check'); }


  myFunction() {
     alert('your form is submitted');
 }

}

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

The Ionic framework has a defined variable

In my code, I have initialized a variable inside the constructor like this: constructor(public http: HttpClient) { this.data = null; this.http.get(this.url).subscribe((datas: any) => { this.dbUrl = datas[0].db_url2; console.log(this ...

service.js was identified as registered, however, it did not run as expected

I clicked on this link for my angular 2.0 tutorial journey. I managed to successfully display the list of drugs, but encountered an issue when I attempted to create the AuthorComponent. Unfortunately, my app stopped running due to the following error: Er ...

Extend the row of the table according to the drop-down menu choice

I am working on a feature where a dropdown menu controls the expansion of rows in a table. Depending on the option selected from the dropdown, different levels of items need to be displayed in the table. For example, selecting level 1 will expand the first ...

Having trouble with Angular router.navigate not functioning properly with route guard while already being on a component?

I am currently troubleshooting an issue with the router.navigate(['']) code that is not redirecting the user to the login component as expected. Instead of navigating to the login component, I find myself stuck on the home component. Upon adding ...

Initialization issue detected in Angular's module APP_INITIALIZER

In my auth module, I have implemented a mechanism to import and set up MSAL configuration before initializing the app. I am using APP_INITIALIZER to delay the initialization of the app until the configuration for MSAL-ANGULAR is retrieved. The issue I am f ...

Displaying tooltips with ngx-charts in Angular

Currently, I am working on developing a unique legend component that features individual material progress bars for each data entry. My goal is to display the pie chart tooltip when hovering over any of the entries within this custom legend. Below is a sn ...

What is causing this JavaScript alert to malfunction?

My current project involves working with ASP.NET and in the view, I have a code snippet that is causing some issues. When I attempt to use Sweet Alert outside of the function, it works perfectly fine. Similarly, if I switch out Sweet Alert for a regular al ...

Despite enabling CORS for a specific origin, I am still encountering the error message "No 'Access-Control-Allow-Origin'"

In my front-end application, I am using Angular to request API responses from a web API core project. Despite setting up cross-origin resource sharing for both running on different origins, I am still encountering an error stating 'No Access-Control-A ...

Tips for refreshing a component after fetching a new page using the useQuery function

Attempting to retrieve and display data from my custom API using axios and react-query's useQuery. The API incorporates pagination, and I have implemented a table with an option to select the page that displays the current data. Everything functions c ...

Setting a default value for Angular Material Autocomplete with a value extracted from a database

Is there a way to retrieve a value from a database and automatically set it as the default value in an autocomplete input field? Fetch clientTypes clientTypes: any[] = []; getClientTypes() { this.clientService.getClientTypes() .subscribe((data: a ...

Managing a project with multiple tsconfig.json files: Best practices and strategies

I've got a project structured in the following way: \ |- built |- src |- perf |- tsconfig.json |- typings |- tsconfig.json My main tsconfig.json looks like this: "target": "es6", "outDir": "built", "rootDir": "./src", Now, I need to have a ...

Do const generics similar to Rust exist in TypeScript?

Within TypeScript, literals are considered types. By implementing const-generics, I would have the ability to utilize the value of the literal within the type it belongs to. For example: class PreciseCurrency<const EXCHANGE_RATE: number> { amount ...

The message I received from my Angular 7 application is indicating that 'The specified selector does not correspond to any elements in the document.'

Using Angular 7 and I've implemented a custom component located at src/app/organization/organization.component.ts import { Component, OnInit } from '@angular/core'; import {FormGroup, FormBuilder, Validators} from "@angular/forms"; @Compo ...

Develop an NPM package by bundling various Angular2 components tailored for a CRUD (Create, Read

I am new to Angular2 and have successfully developed three components for managing employees: create/edit, view, and list. The component selectors are <create-employee>, <view-employee>, <list-employee>. My goal is to create a single npm ...

How can I make ngFor update after an object has been modified?

I'm currently working on a function that updates an object property after an item is dropped in a drag and drop scenario. However, it seems like either my function is incorrect or there might be something else that needs to be done because the display ...

Updated the application to Angular 6 but encountered errors when attempting to run npm run build --prod. However, running the command npm run build --env=prod was executed without any issues

Running the command npm run build -- --prod results in the following error messages: 'PropertyName1' is private and can only be accessed within the 'AppComponent' class 'PropertyName2' does not exist in type 'AppCompo ...

Setting up *ngFor with a freshly created array_INITIALIZER

Angular v5 In my search component, I am encountering an issue where the *ngFor directive is throwing an error because the "searchResults" array is initially empty on page load. This array is populated with data from a service returning a promise of search ...

Validation of Date in Angular 5 (with specified minimum and maximum dates)

Struggling to find a simple solution for this issue, I have a date input like the following: <input [(ngModel)]="toolDate" type="text" class="tool_input tool_input__date"> To control the input and restrict it to only accept dates, I am using . In m ...

What sets apart TypeScript's indexed types from function signatures?

I am curious about the distinction between indexed type and function signatures in TypeScript. type A = { _(num: number): void; }['_']; type B = { _(ten: 10): void; }['_']; let a: A = (num) => { console.log(num); }; let b: B ...

Experimenting with Nuxtjs application using AVA and TypeScript

I'm in the process of developing a Nuxt application using TypeScript and intend to conduct unit testing with AVA. Nonetheless, upon attempting to run a test, I encounter the following error message: ✖ No test files were found The @nuxt/typescrip ...