Home > Back-end >  Simulate click with javascript with no element ID
Simulate click with javascript with no element ID

Time:01-31

<button 
   type="button" 
    
   data-events="click:onAddNote" 
   data-events-target="cpoe-LabResultDetailView"
>
   Add Note
</button>

I'm trying to simulate / prompt a click of this button when I press a shortcut key sequence. However, I haven't been successful with anything other than through the class "blue", which works but also activates something else. How do I target the "data-events" or "data-events-target"?

Is there a way to something similar to: $("click:onAddNote").trigger("click");

CodePudding user response:

You can use querySelector and select the button with its attributes

var button = document.querySelector('[data-events="click:onAddNote"]');
button.onclick = ()=>console.log('Clicked');
button.click()
<button 
   type="button" 
    
   data-events="click:onAddNote" 
   data-events-target="cpoe-LabResultDetailView"
>
   Add Note
</button>

CodePudding user response:

Why not just this?

const button = docuemnt.querySelector('button')
button.click()

CodePudding user response:

There are many ways to select the <button> element.

Method-1

In the example below, the click event is fired by selecting the first <button> element with the .blue class style applied.

let button = document.getElementsByClassName('blue');

button[0].addEventListener('click', function() {
  console.log("clicked");
});
<button type="button" >Add Note</button>

Method-2

The click event of the <button> element with the .blue class style applied using jQuery can be rendered as follows:

$(".blue").on('click', function(event) {
  console.log("clicked");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button type="button"  data-events="click:onAddNote" data-events-target="cpoe-LabResultDetailView">Add Note</button>

CodePudding user response:

Targeting the "data-events" attribute is simple, like this ...

$('button[data-events="click:onAddNote"]').on('click', function(){
  console.log('clicked!');
});
<button 
   type="button" 
    
   data-events="click:onAddNote" 
   data-events-target="cpoe-LabResultDetailView"
>
   Add Note
</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

See the jquery documentation for more information on running handlers -- Here

  •  Tags:  
  • Related