Mirko
Mirko

Reputation: 31

How to simulate a mouse click in Javascript

I have the following elements:

<input type="submit" name="add" value="add item" class="btn btn-add" onclick="addItem('add');return false;">

I want to write a Javascript to simulate a click of a mouse to add item to my shopping basket I know you can use document.getElementById('add').click() but there's no Id here

I am very new to this and any help would be much appreciated

Upvotes: 3

Views: 250

Answers (6)

BonifatiusK
BonifatiusK

Reputation: 2331

You might want to use jQuery for this. Using jQuery you can trigger a click like this:

$('#id').trigger('click');

In case you don't have an id but do have a class it might look like this:

$('.btn-add').trigger('click');

And of course with jQuery you can look at the parent dom element and 'find' the element you are looking for. eg:

$('#parentElement').find('button').trigger('click');

kudo's to mplungjan who came with:

$("input[name='add']").trigger('click');

another way you can find here:

see the fiddle

Upvotes: 0

mplungjan
mplungjan

Reputation: 177885

Here are some possibilities

document.getElementsByName("add")[0].click();

where 0 is the first element on the page named add.

var form = document.getElementsByTagName("form")[0]; // change 0 to reflect the form
form.elements[form.elements.length-1].click(); // clicks the last button in the form

Alternative

document.forms[n].elements[m].click(); 

where n is the 0 based index of the form on the page and m is the 0 based index of the element in that form

Upvotes: 0

pat
pat

Reputation: 5797

Get the element by class

var elem = document.getElementsByClassName('btn-add');

Then call click on it

elem[0].click()

Upvotes: 0

stanze
stanze

Reputation: 2480

Try using below javascript code.

   document.addEventListener("click", function(){
        document.getElementById("ID").innerHTML = "Click Event";
    });

Upvotes: 0

user3284566
user3284566

Reputation: 83

You can use Jquery library https://jquery.com

and in the code:

$( "input[name='add']" ).click();

Upvotes: 0

Jens
Jens

Reputation: 69440

If you only have on element with name "add" you can also use:

document.getElementsByName('add')[0].click() 

Upvotes: 3

Related Questions