Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically click on a button - maybe Angular?

I'm trying to click on a html button programmatically.

Looking at the page source - I see

<div class="submitBtns">
    <button class="btn btn-primary primaryBtn" type="button">Search</button>
</div>

I don't think this is standard html - maybe an extension.

I can get to the button object - but calling obj.click() on it doesn't work.

The document also has this header - maybe that'll identify the document type - also has a lot of class names starting with ng- prefix.

<meta http-equiv="X-UA-Compatible" content="IE=edge">

More info...this is a third party web-page and I'm injecting javascript into it.

I entered something into an INPUT field and then would like to simulate a button press.

Pure javascript.

like image 624
dashman Avatar asked Aug 28 '26 15:08

dashman


2 Answers

Created a Sample Demo in Stackblitz for Reference

In Angular, we can get access to any HTML elements using @ViewChild &ElementRef. We also have to add an unique identifier by prefixing # in the HTML element that you want to access programmatically.

In HTML:

<button class="btn btn-primary primaryBtn" #search type="button">Search</button>

In TS:

import { Component, ViewChild, ElementRef } from '@angular/core';
.
.
export class YourComponent{
.
.
    @ViewChild('search') search: ElementRef;
.
.
.
.   // In your function
    this.subContent.nativeElement.click();
}
like image 184
Guhan S Avatar answered Aug 30 '26 05:08

Guhan S


JavaScript Option

If you want to do this with pure JavaScript you could add an ID to the button and do this:

document.getElementById("myButton").click();

jQuery Option

If I were to do this with jQuery I would write this piece of code:

<script>
$(document).ready(function() {
   $('.submitBtns button').click();
});
</script>

Now the problem with this is that if you have several forms on your page it would click all of the buttons that are identified using the $('.submitBtns button').click(); selector. You could probably add an ID to this button if you have access to the code. And just change it to:

<script>
$(document).ready(function() {
   $('#myButton').click();
});
</script>

If you require to simulate a click to trigger events related to the click, but not actually click the button, you could use $("#myButton").trigger("click");.

like image 31
Mihail Minkov Avatar answered Aug 30 '26 06:08

Mihail Minkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!