3

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

2
  • This question is already answered. Please chk stackoverflow.com/questions/4571497/… Commented Apr 24, 2015 at 11:17
  • That duplicate is the oldest on this site I think. It is not the best duplicate Commented Apr 24, 2015 at 11:31

6 Answers 6

3

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

document.getElementsByName('add')[0].click() 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I've entered your script into the browser and this is what I am getting: Uncaught ReferenceError: addItem is not defined
0

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

and in the code:

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

Comments

0

Try using below javascript code.

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

Comments

0

Get the element by class

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

Then call click on it

elem[0].click()

Comments

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

Comments

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

1 Comment

$("input[name='add']") would also be a way

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.