Accessing <form> content in event handler after submit <button> is clicked that exists outside of <form>

Viewed 332

It's possible to have a <button> outside of the <form> element and tie it to the relevant form using the for attribute. I'm doing this because I want to include a fontAwesome icon in the button, which I cant do with <input> since <input> is a void element(no closing tag). However, If I want to tie an event handler to the form submit event, the event isn't recognized. Why is that? The click event on the button works, but that wont give me access to the form's data.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css"
      integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w=="
      crossorigin="anonymous"
    />
  </head>

  <body>
    <form id="form0">
      <input type="text" name="title" />
      <input type="text" name="id" />
    </form>
    <button type="submit" for="form0"><i class="fas fa-cart-plus"></i></button>
    <form id="form1">
      <input type="text" name="title" />
      <input type="text" name="id" />
    </form>
    <button type="submit" for="form1"><i class="fas fa-cart-plus"></i></button>
  </body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="js/test.js"></script>
</html>

//This works
$(document).on("click", "button", function (event) {
  console.log("running click event handler");
});

//This doesn't
$(document).on("submit", "form", function (event) {
  console.log(
    "running submit event handler, serilized data is: " + $(this).serialize()
  );
});
1 Answers

You can use $(this).prev().serialize() to access form above button and get value of that form .

Demo Code:

$(document).on("click", "button", function(event) {
  console.log("running click event handler");
  console.log(
    "running submit event handler, serilized data is: " + $(this).prev().serialize()
  );
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Document</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w==" crossorigin="anonymous" />
</head>

<body>
  <form id="form0">
    <input type="text" name="title" />
    <input type="text" name="id" />
  </form>
  <button type="submit" for="form0"><i class="fas fa-cart-plus"></i></button>
  <form id="form1">
    <input type="text" name="title" />
    <input type="text" name="id" />
  </form>
  <button type="submit" for="form1"><i class="fas fa-cart-plus"></i></button>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</html>

Related