user3355028
user3355028

Reputation: 177

Submitting a form with a button using JS/Jquery

I'm new with JS and I have a very simple question. I want to submit a form with a button which located outside of it.

The form header looks like this:

<form action="http://www.google.com" method="get" id="myform">

The button looks like this:

<input type="button" value="Click Me" id="send">

The JS file is:

document.getElementById("send").onclick = function() {
    document.getElementById("myform").submit();
};

And it is not working. When I clicked the button nothing happens. Any idea? Jquery will be also fine for me instead of vanilla JS.

Appreciate your help.

Thanks

Upvotes: 0

Views: 101

Answers (4)

vickisys
vickisys

Reputation: 2036

 <script type="text/javascript">
$(document).ready(function(){			
	$("#send").on("click",function () {
		$('#myform').submit();
		 });
	    });
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

hope this will help you.since your showing google page on button click.

Upvotes: 1

Shadowind
Shadowind

Reputation: 114

I Prefer using JQuery to submit a form.

There are other posts on stackoverflow covering the topic of submitting a form using JQuery. You can check out this one Submit form using jquery

If I may add something that might come in handy if you have validators on the form, for required fields for example. You could add a check before you submit the form to see if all the fields are valid. Your button click method may look something like this:

function SubmitButtonClick(){
    var form = $('#myForm');
    form.validate();
    if(!form.valid())
      return false;
    else
      form.submit();
})

Obviously you should just remember to add the method to the button's onclick like so:

<input type="button" value="Click Me" id="send" onclick="SubmitButtonClick()" />

Upvotes: 0

Pawnesh Kumar
Pawnesh Kumar

Reputation: 494

try this:

window.onload = function(){
document.getElementById("send").onclick = function() {
    document.getElementById("myform").submit();
};}

or

document.getElementById("send").onclick = function() {
document.getElementById("myform").submit();}

after

<input type="button" value="Click Me" id="send">

Upvotes: 0

Leonidas
Leonidas

Reputation: 566

You can try get the id of the form. And you call it from wherver you want.

Try:

$(".button").click( function() {
    $('#myform').submit();
});

Upvotes: 0

Related Questions