简体   繁体   中英

Javascript press button

Hey I'm working on a little script that will make something easier for me. What I have is an html form to submit something. What I want to happen is when I press the submit button, it travels to a different location and presses a button for me. How can I do this?

Assuming that the "different location" is another element on the same page, you should attach an event listener to the form's submit event. This listener will trigger a click on your "different location" target element.

<form id='myForm'>
...
</form>

<script>
$('form#myForm').bind('submit', function() {
    $('#otherElement').trigger('click');
});
</script>

If you use a Javascript framework like jQuery , then you can bind some javascript function to the "submit event", which occurs when your user submits the form. Inside that javascript function you can do whatever you want, including make changes to the current webpage and do 'click' events on other elements as well.

Your code might look something like:

$('form').submit(function() {
    $('some_other_html_elem').click();
})

If you mean to press a button in another page, you can use this in the destination page:

$(document).ready(function() {
  $("#button").click();
});

Here is an actual answer (Using JS, not Jquery):

So both buttons will do the same, but the second one actually presses the first one using JS.

<button id="hackerbtn" onclick="alert('I am a a hacker hahaha')">So this is your button</button>

<button onclick='document.getElementById("hackerbtn").click()'>Press above button using JS</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM