Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can you access a HTML form data from the event property, or a "this" keyword, in javascript?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading