Add Note I'm trying to simu" /> Add Note I'm trying to simu" /> Add Note I'm trying to simu"/>

Simulate click with javascript with no element ID

1k Views Asked by At
<button 
   type="button" 
   class="blue" 
   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");

4

There are 4 best solutions below

0
Musa On BEST ANSWER

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" 
   class="blue" 
   data-events="click:onAddNote" 
   data-events-target="cpoe-LabResultDetailView"
>
   Add Note
</button>

0
ManuelMB On

Why not just this?

const button = docuemnt.querySelector('button')
button.click()
0
Sercan On

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" class="blue">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" class="blue" data-events="click:onAddNote" data-events-target="cpoe-LabResultDetailView">Add Note</button>

0
Petr Fořt Fru-Fru On

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

$('button[data-events="click:onAddNote"]').on('click', function(){
  console.log('clicked!');
});
<button 
   type="button" 
   class="blue" 
   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