Javascript get form value on submit

How to Get HTML Form Fields on Submit Event in JavaScript?

Let’s suppose you have the following HTML element:

To get any field by its name or index (when a submit event is triggered), you can do any of the following:

Accessing Form Fields via HTMLFormElement.elements on Submit Event

When a submit event handler is attached to a element, event.target refers to the element itself. Therefore, you can access form fields by using their name or index on the HTMLFormElement.elements object (or the event.target.elements object in this case), for example, like so:

This works because the HTMLFormElement.elements property actually returns an HTMLFormControlsCollection object, which allows accessing of all the form fields contained within the element by using the element’s name and/or index.

The HTMLFormControlsCollection object also has the following methods for accessing form fields:

  • HTMLFormControlsCollection.namedItem(name) (or HTMLFormElement.elements.namedItem(name) );
  • HTMLFormControlsCollection.item(index) (or HTMLFormElement.elements.item(index) ).
Читайте также:  js .html demo

The main difference between the two — i.e. accessing the form fields directly on the HTMLFormControlsCollection object versus doing so via the above-mentioned methods — is the fact that the former would return undefined if the element doesn’t exist, while the latter would return null .

Therefore, as an alternative, you can also access form fields via these methods as shown below:

Directly Accessing Form Fields on Submit Event

When a submit event handler is attached to a element, event.target refers to the element itself. Therefore, you can directly access the form fields by using their name or index directly on the event.target object, for example, like so:

This might not be the best approach as properties can get mixed up with other attributes specified on the element. Instead, using form.elements property might be a better approach as it only returns the form fields contained within the element.

Hope you found this post useful. It was published 14 Sep, 2022 . Please show your love and support by sharing this post.

Источник

Get HTML Form Data In Javascript (Simple Examples)

Welcome to a quick tutorial on how to get the HTML form data in Javascript. So you have an HTML form but want to do the processing in Javascript instead?

  1. Create the HTML form as usual – Give the form an ID, and attach a name to the input fields.
    • Create a form data object, and feed the HTML form in as a parameter.
      • var form = document.getElementById(«demo»);
      • var data = new FormData(form);
    • Lastly, manually append more keys/values if required – data.append(«KEY», «VALUE»);

That covers the quick basics, but read on for more examples!

TLDR – QUICK SLIDES

How To Get HTML Form Data In Javascript

TABLE OF CONTENTS

JAVASCRIPT GET FORM DATA

All right, let us now get into the examples of how to get the form data in Javascript.

EXAMPLE 1) GET FORM DATA & AJAX POST

       
  1. Create the HTML as usual.
  2. Create a new FormData(HTML FORM) object, and submit it to the server “as usual”.

EXAMPLE 2) GET FORM DATA & URL PARAMS

       
  • (A & B1) The “usual HTML form” and create var data = new FormData(HTML FORM) .
  • (B2) Then, “convert” into var params = new URLSearchParams(data) .
  • (B3) Attach the parameters to the end of the URL – «http://site.com?» + params.toString() , and submit the form.

EXAMPLE 3) MORE FORM DATA

     
  • (A) Take note that the HTML form now has a “custom widget”.
  • (B1) Since the “custom widget” is not the usual , var data = new FormData(FORM) will not automatically adapt data from it.
  • (B2) To “fix” that, we can use data.append(«KEY», «VALUE») to manually add more data entries.
  • (B3) Now, the FormData object is not some “black hole”. You put data in and have no idea what’s inside.
    • get(KEY) Returns the value of the specified KEY .
    • has(KEY) Checks if the dataset contains KEY .
    • key() Return all the keys in an array.
    • values() Return all the values in an array.
    • entries() Returns all the keys and values in an array.

    DOWNLOAD & NOTES

    Here is the download link to the example code, so you don’t have to copy-paste everything.

    SUPPORT

    600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

    EXAMPLE CODE DOWNLOAD

    Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

    That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

    INFOGRAPHIC CHEAT SHEET

    THE END

    Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

    Leave a Comment Cancel Reply

    Breakthrough Javascript

    Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

    Socials

    About Me

    W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

    Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

    Источник

    Извлечение данных из HTML формы с помощью JavaScript

    Извлечение данных из HTML формы с помощью JavaScript

    Прежде чем пересылать данные на сервер, введенные пользователем в поля формы на сайте, нужно научится их извлекать. И с этой задачей JavaScript умеет отлично справляться. Существует несколько способов получения данных из HTML форм, но мы в рамках данного урока рассмотрим самый понятный для новичков метод.

    HTML + CSS код

    Все элементы управления и поля формы должны обязательно находится внутри тега form.

    body font-family: sans-serif;
    font-weight: 700;
    background-color: yellow;
    >

    form button margin-top: 10px;
    font-weight: 700;
    padding: 10px 20px;
    font-size: large;
    >

    Получение данных из HTML формы с помощью JavaScript.

    JavaScript код

    После создания формы в HTML, мы можем обратится к элементу form для получения введенных пользователем данных через JavaScript. Наша форма состоит из четырех полей: name, age, terms, plan и одной кнопки submit. Найдем все поля формы по отдельности через селектор, получим данные и запишем их в объект. В дальнейшем этот объект будет передаваться на сервер.

    Найдем элемент form по идентификатору с помощью метода document.getElementById.

    const form = document.getElementById(‘form’);

    При отправки формы сработает событие submit, которое мы будем отслеживать при помощи слушателя addEventListener. Передадим первым параметром отслеживаемое событие submit (клик по кнопке), а вторым параметром название callback-функции. Данная функция запустится сразу после клика по кнопке.

    После нажатия на кнопку Отправить, браузер перезагрузится, что нежелательно. Поэтому отменим дефолтное поведение браузера с помощью метода preventDefault (предотвратить действия по умолчанию). Передадим объект события в аргументах функции и вызовем метод preventDefault для события event.

    function getFormValue(event) event.preventDefault();

    Что должна делать функция getFormValue? Внутри функции мы получим поля формы и извлечем из них значения.

    const name = form.querySelector(‘[name=»name»]’), //получаем поле name
    age = form.querySelector(‘[name=»age»]’), //получаем поле age
    terms = form.querySelector(‘[name=»terms»]’), //получаем поле terms
    plan = form.querySelector(‘[name=»plan»]’); //получаем поле plan

    Создадим объект, в который запишем полученные нами данные. Их текстовых полей получим значения data, а из поля с типом checkbox нам нужно получить состояние checked (отмеченную галочку).

    const data = name: name.value,
    age: age.value,
    plan: plan.value,
    terms: terms.checked
    >;

    Для проверки, выведем в консоль объект data.

    После нажатия на кнопку Отправить, мы увидим полученные значения из формы в виде объекта, готовые для передачи их на сервер.

    Получение данных из HTML формы с помощью JavaScript.

    Выводы

    Такой способ очень простой для начинающих, но он лишен гибкости. Ведь мы должны явно указать все поля формы в JavaScript коде, а что если со временем появятся новые поля? Тогда придется программисту при каждом добавлении нового поля, дописывать код.

    Создано 19.04.2021 10:23:15

  • Михаил Русаков

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

Порекомендуйте эту статью друзьям:

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

  1. Кнопка:
    Она выглядит вот так:
  2. Текстовая ссылка:
    Она выглядит вот так: Как создать свой сайт
  3. BB-код ссылки для форумов (например, можете поставить её в подписи):

Комментарии ( 0 ):

Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

Источник

Оцените статью