Abdul Rehman
Abdul Rehman

Reputation: 1794

Why Form doesn't submit with javascript if an input field's name is submit

Why Form doesn't submit on event if input field name is submit. I already know it won't based on recent experience, but why not.

http://jsfiddle.net/btm5j599/1/

Edited Code

$('#btn1').click(function() {
  $('#form1').attr('action', '');
  $('#form1').submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<form action="http://mytestsite.com/test/" method="post" id='form1'>
  <span>This is a form content</span>
  <input type="submit" name="submit" value="Submit" />
</form>

<hr>

<button id="btn1">Submit form on same page</button>

Upvotes: 1

Views: 1716

Answers (4)

Karl Gjertsen
Karl Gjertsen

Reputation: 4928

The problem is that the submit button has the name submit and this clash is overriding the form's submit() function.

If you remove the name="submit" attribute, this will work.

Here is some more information on conflicts:

http://jibbering.com/faq/names

http://paulsec.github.io/blog/2014/03/09/dealing-with-html-submits-conflict

Upvotes: 2

wolfhammer
wolfhammer

Reputation: 2661

Run the following modified submit along with a javascript console. There is a cross-origin policy error and also you were missing http://.

  $('#form1').submit(function(event) {
    console.log(this.action);
    var action = this.action
    $.post(this.action, $(this).serialize()).done(function(data, status, xhr) {
      alert(action + "\n\n" + status);
    }).fail(function(xhr, status, err){
      alert(action + "\n\n" + status);
    });
  });

  $('h3').click(function() {
    $('#form1').submit();
  });
https://code.jquery.com/jquery-1.11.3.min.js
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="http://www.google.com" method="post" id='form1'>
  <input type="submit" name="submit" value="Submit" />
</form>

<h3>click</h3>

Upvotes: 1

Sundaze
Sundaze

Reputation: 305

Why do you need the js when you have an action that goes to www.google.com ? What are you trying to do ?

If it's just a sample, I still don't understand why you need an input with the type submit? You can have the button without a form and then run the js. But you can't run both because when you klick the input, it will bring you to google.com without running the js. But you could open it in a new tab and then the js would run.

Upvotes: 1

RiccardoC
RiccardoC

Reputation: 866

You can try to put an hidden button (input type="submit") and trigger a "click" event on it instead of a "submit" event on the form

Upvotes: 3

Related Questions