2

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

TZHX
  • 5,291
  • 15
  • 47
  • 56
Mirko
  • 21
  • 1
  • This question is already answered. Please chk http://stackoverflow.com/questions/4571497/click-a-button-named-submit-in-javascript – Ramkumar Apr 24 '15 at 11:17
  • That duplicate is the oldest on this site I think. It is not the best duplicate – mplungjan Apr 24 '15 at 11:31

6 Answers6

2

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

document.getElementsByName('add')[0].click() 
Jens
  • 67,715
  • 15
  • 98
  • 113
  • Thanks I've entered your script into the browser and this is what I am getting: Uncaught ReferenceError: addItem is not defined – Mirko Apr 24 '15 at 12:23
0

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

Community
  • 1
  • 1
BonifatiusK
  • 2,281
  • 5
  • 29
  • 43
0

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

and in the code:

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

Try using below javascript code.

   document.addEventListener("click", function(){
        document.getElementById("ID").innerHTML = "Click Event";
    });
stanze
  • 2,456
  • 10
  • 13
0

Get the element by class

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

Then call click on it

elem[0].click()
pat
  • 5,757
  • 5
  • 25
  • 30
0

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

mplungjan
  • 169,008
  • 28
  • 173
  • 236