Home > Enterprise >  Can you access a HTML form data from the event property, or a "this" keyword, in javascrip
Can you access a HTML form data from the event property, or a "this" keyword, in javascrip

Time:07-15

I know that you can easily get data from a form like:

function getData(event) {
        event.preventDefault();
      const inpt = document.getElementById("inpt").value;
        return inpt;
}

//OR

function getData(event) {
        event.preventDefault();
      const inpt = document.getElementById('form').elements[0].value;
        return inpt;
}
<form id="form" onsubmit="getData(event)">
      <input id="inpt" type="text"></input>
</form>

what I'd like to know is if this same value could be reached through the event property or a this keyword, withou using a "getElementBy..." of any sort or any querySelector.

CodePudding user response:

I think I like James' answer better. Much simpler. Haven't tested either too extensively sorry.

If you assign all of your form elements a name attribute, on the form submission event you can use the FormData Api to get their data. I believe this won't work on I.E. or other older browsers (check for browser compatibility).
Form Data: https://developer.mozilla.org/en-US/docs/Web/API/FormData#browser_compatibility
Object.fromEntries(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries#browser_compatibility

<form id="form" onsubmit="getData()">
      <input name="input1" id="inpt" type="text"></input>
      <input name="input2" id="NotNeededForThis" type="text"></input>
</form>
function getData(event) {
        event.preventDefault();
        const formData = new FormData(event.target);
        const formObject = Object.fromEntries(data.entries());
        return formObject;
}

This will return the object:

{
    input1: "whatever the value was",
    input2: "whatever the value was"
}

CodePudding user response:

Since the event listener is set on the form, the form element is available as

event.target

And so the text field value would be accessible by

event.target.elements[0].value

The form element is also this within the submit handler, so you could also do

this.elements[0].value.

  • Related