Không thể submit form programmatically khi form có 1 input[name=submit]

:V :V :V sao xóa cái name="submit" ở nút Submit thì lại chạy được??? :V

thấy nó submit dư cái submit=Submit ngứa mắt xóa thì ko cần nhấn submit 2 lần nữa???

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function getTokenFromApi(){
  await sleep(200); // or ajax, ...
  let success = {
 	error: false,
 	value: '1234567890'
  };
  let error = {
 	error: true,
 	value: 'Something wrong on our end'
   };
   return success;
}

async function addTokenFromAPI (e) {
  e.preventDefault();
  getTokenFromApi().then(res => {
    if (res.error) {
      alert(res.value);
    } else {
      $('<input>')
          .attr('type','hidden') 
          .attr('name', 'token') 
          .val(res.value) 
          .appendTo('form');
      $("form").unbind('submit').submit();
    }
  });
}

$(document).ready(function(){
  $("form").on('submit', addTokenFromAPI);
});
</script>
</head>
<body>

<form action="/action_page.php">
  First name: <input type="text" name="FirstName" value="Mickey"><br>
  Last name: <input type="text" name="LastName" value="Mouse"><br>
  <input type="submit" value="Submit"> <!-- xóa name="submit" ở đây -->
</form> 

</body>
</html>

gg xem https://stackoverflow.com/questions/5651933/what-is-the-opposite-of-evt-preventdefault ngược lại với preventDefault là gì =] thì thấy đúng là họ xài unbind submit rồi submit lại, nhưng có 1 comment

Another option in this scenario might be to use input type=“button” and bind to the click event instead of using input type=“submit” and binding to the submit event.

input type button là thế nào =] mình mới đi xóa thử cái name=“submit” kia đi thì lại ko cần nhấn 2 lần nữa :V :V :V

code ban đầu cũng chỉ cần xóa name=“submit” đi là ko còn bị click 2 lần, tại sao lại bị như vậy :V :V

đây :V

I know that using $('form').submit() does not work when the submit button is named with the reserved name “submit”.

jquery “feature” :rofl:

nếu submit button có name là “submit” thì gọi $('form').submit() nó ko chạy, nên bấm lần 1 chỉ chạy unbind handler kia ra thôi, .submit() sau đó ko có tác dụng. Bấm lần thứ 2 ko đụng tới js, handler đã được unbind ra thì nó submit thẳng.

Doc jquery: https://api.jquery.com/submit/

Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit , length , or method . Name conflicts can cause confusing failures. For a complete list of rules and to check your markup for these problems, see DOMLint.