3

When I use method click() to click the button, the submission failed.
But, when I use the mouse to click the button on that webpage, (the submit form is same) it works.

HTML file:

<button xmlns="http://www.w3.org/1999/xhtml" class="ui-button button1"       type="submit" id="create">
    <span>
        <span>Create</span>
    </span>
</button>

My userscript file:

document.getElementById("create").click();

How do I click the button using HTML DOM click()?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
CodeCat
  • 161
  • 1
  • 5
  • 8

4 Answers4

1

maybe instead of clicking the button. You can submit the form in javascript as

document.getElementByName('form1').submit();

as it fulfills your requirement.

Ashish Chopra
  • 1,413
  • 9
  • 23
  • Good thinking, except that no form was indicated in the question, and the ` – Brock Adams Apr 14 '13 at 09:40
0

Wrap the call in an anonymous self executing construct like so:

(function(){
    document.getElementById("create").click();
})();

This will simulate a click when the javascript is loaded.

Christian-G
  • 2,371
  • 4
  • 27
  • 47
0

The click method does not always work. Try sending a click event similarly to this answer:

var targBtn     = document.querySelector ("#create");
var clickEvent  = document.createEvent ('MouseEvents');
clickEvent.initEvent ('click', true, true);
targBtn.dispatchEvent (clickEvent);

But also beware that the button may not operate on clicks at all.   See "Choosing and activating the right controls on an AJAX-driven site".

The button may operate on mousedown, mouseup, or some combination of events. Use the techniques from that question to activate the control. Link to the target page if you can't get it to work.

Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
  • 1
    thanks all the same .I solved it use settimeout. window.setTimeout(function () { document.getElementById("button-create").click(); }, 3000) Because click() is too quick to get one property in the form,so it failed – CodeCat Apr 14 '13 at 10:35
  • Glad you got it working. If you let us know that the content is added by javascript (AJAX), then you'll get better & faster answers next time. – Brock Adams Apr 14 '13 at 11:06
0

if at all you are flexible about value of your button then do this:

<button xmlns="http://www.w3.org/1999/xhtml" class="ui-button button1" value="submit" type="submit" id="create">

document.getButtonByValue('submit').click();

This works just fine.

jsfiddle link

Ashish Chopra
  • 1,413
  • 9
  • 23