0

i'm creating a system than get html form values and send it to API. I created a simple html form with javascript to get values to send, but i get form using form ID, is there any way to get form without id ? i'll creating this to work in website than have only one .

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="teste1.js"></script>
</head>
<body>
    <form id="myForm">
        <label for="myName">Send me your name:</label>
        <input id="myName" name="name" value="John"><br>
        <label for="myEmail">Send me your email:</label>
        <input id="myEmail" name="email" value="Exemplo@exemplo.com"><br>
        <input type="submit" value="Send Me!">
      </form>
</body>
</html>

teste1.js

window.addEventListener( "load", function () {
    function sendData() {
      const XHR = new XMLHttpRequest();
      const FD = new FormData( form );

      const data = {

        name: FD.get('name'),
        email: FD.get('email')

      }

      // Define what happens on successful data submission
      XHR.addEventListener( "load", function(event) {
        alert("Success.");
      } );

      // Define what happens in case of error
      XHR.addEventListener( "error", function( event ) {
        //alert( 'Oops! Something went wrong.' );
      } );

      // Set up our request
      XHR.open( "POST", "API_URL" );
      XHR.setRequestHeader('Content-type', 'application/json')
      // The data sent is what the user provided in the form
      XHR.send(JSON.stringify(data));
  }
 
  // Access the form element...
  const form = document.getElementById( "myForm" );

  // ...and take over its submit event.
  form.addEventListener( "submit", function ( event ) {
    event.preventDefault();

    sendData();
  } );
} );

look i get form with

const form = document.getElementById( "myForm" );

and

const FD = new FormData( form );

how get form without id, if it was like

<form>
...

1 Answers1

0

You may try document.forms[0] And if you have name assigned to form then it can be through, let say it something like

<form name="myform"></form>

document.forms.myform
Asutosh
  • 1,775
  • 2
  • 15
  • 22