To find the action attribute and method of a form in JavaScript

How to find the action attribute and method of a form in JavaScript?

In HTML, there is element which has few attributes: input, label, text area, select, name, target. The action and method attributes of the form are used to return those values. The action attribute also specifies where to send the form data when form is submitted.

To get a better idea of this concept, let’s look into the examples where we achieved the given task using action attribute and also with method attribute.

Using action attribute

The JavaScript action attribute will specify what to perform when a form is submitted.

Syntax

The syntax to display the action attribute of the form is shown below.

document.getElementById('formID').action;

We can set or get the value of action attribute in the form. The action attribute specifies what to perform when a form is submitted. The URL is provided as a value inside the action attribute. The URL can be an absolute URL (which includes the domain name) or relative URL (which refers a file within a website).

Example 1

The following is an example program to display the action attribute of a method.

       Full name:  
password:

On executing the above code, the following output is generated.

Example 2

The following is an example program to set the value for action attribute of a form.

       Full name:  
password:

On executing the above code, the following output is generated.

Using the method attribute

The syntax to display the method attribute of the form is shown below.

Document.getElementById('formID').method;

The HTTP method to submit the form. The possible method values are post, get and dialog.

  • get method − This is the default method. The form data is attached to the URL inside the action and the form data that is submitted is visible to the users. It is not secure.
  • post method − The form data is attached to the HTTP request body and the form data that is submitted is not visible to the users.
  • dialog method − Here, the form is inside a dialog.

Example 1

Let us look at an example program to display the use of get method.

       Full name:  
password:

On executing the above code, the following output is generated.

On clicking the submit button, the below output is generated. The name and password are visible using the get method.

Example 2

The following is an example program to display the use of the post method.

       Full name:  
password:

On executing the above code, the following output is generated.

On clicking the submit button, the below output is generated. The form data is not visible to the users using post method.

Источник

JavaScript урок 9. Объектная модель документа (продолжение): идентификация формы

егэ разбор егэ разбор pascal уроки c уроки python уроки c++ уроки vb уроки lazarus уроки php уроки html уроки css уроки javascript уроки jquery и ajax уроки prolog уроки flash уроки

На это уроке рассматриваются все эти понятия, связанные с формой.

Для идентификации формы и ее элементов через javaScript можно воспользоваться двумя атрибутами: name и id .

Пример обращения в javaScript к форме:

Пример: Создать форму с двумя элементами типа radio (переключатели) и кнопкой отправки формы на сервер ( submit ). Получить доступ в скрипте к форме:

form name="f1" id="f"> Ваш пол:br> input type="radio" name="r1" id="id1"br> input type="radio" name="r1" id="id2"br> input type="submit"> /form> /body>
document.forms[0]. // первый элемент массива форм document.getElementById("f"). // объект форма c style="color: #660066;">getElementsByTagName("f1"). // массив объектов с именем f1

document.forms[0]. // первый элемент массива форм document.getElementById(«f»). // объект форма c // массив объектов с именем f1

  • В случае, когда мы используем javaScript для динамичности и интерактивности веб-страниц, но, при этом отправлять данные с формы на сервер не требуется, то для идентификации используется атрибут id .
  • Атрибут name необходим для того, чтобы отправить форму на сервер.
form action=". " method=". " enctype=". " id=". "> input type="text" id=". "> . input type="submit" id=". "> /form>

Атрибуты формы:

action (англ. «действие»)
Файл на сервере с кодом для отработки отосланных данных
https://labs-org.ru/javascript-1/
enctype (англ. «тип кодировки») text/plain (обычный текст)
application/x-www-dorm-urlencoded (для метода Post отправки формы)
multipart/form-data (для метода Post, если прикрепляются файлы)
method (метод отправки данных) post
get
form name="myForm" action="file.php" method="post" enctype="text/plain">
  • В атрибуте action указывается серверный файл со скриптом, ответственным за основную обработку данных, пересылаемых из формы. Обычно код этого файла пишется на серверном языке программирования, например, на языке php или perl.
  • Атрибут enctype указывает на тип передаваемой на сервер информации, если это просто текстовые данные — text/plain , если с формой отсылаются файлы, то следует указать multipart/form-data .
  • Атрибут method указывает и определяет форму передачи данных. Подробно мы на этом останавливаться не будем, однако следует сказать, что для более надежной передачи следует указать метод post .

Пример: Создать несколько различных элементов управления формы, данные из формы предполагается отсылать на сервер

form name="f_name" method="get" action="javascript:void(0);"> input name="i_name" size="30" type="text" value="текст"> textarea name="mess">/textarea> input type="checkbox" name="chName" id="chId" value="yes" />да input type="radio" name="rName" id="rId" value="yes" />да input type="file" name="fName" id="fId" /> input type="password" name="pName" id="pId" /> input type="hidden" name="hName" id="hId" value=“hid"/> select name="sName" id="sId" multiple="multiple" > option name="opt1Name" id="opt1Id" value="1">text1 option name="opt2Name" id="opt2Id" value="2">text2 /select> /form>

При щелчке на кнопке submit данные на сервер будут пересылаться в форме переменная=значения в следующем формате:
i_name = текст
mess = «»
chName= yes
rName = yes
fName = путь файла
pName = «»
hName= hid
sName=1 или 2

О том, как правильно располагать элементы управления на форме с точки зрения юзэбилити, можно прочитать статью на сайте tproger по сслыке1 и ссылке2.

Методы формы

Submit() ~ использование кнопки submit
Reset() ~ использование кнопки reset

Метод submit() формы применяется для отправки формы из JavaScript-программы

Пример того как можно в javascript отправить форму по щелчку на гиперссылке:

Пример: Создать форму с текстовым полем. После формы расположить гиперссылку, по щелчку на которой отсылать данные формы на сервер

form name="s" method="post" action=  "javascript:window.alert('данные подтверждены'); void(0);"> input type="text" size="1"> /form> a href="javascript:document.s.submit();">Отослать/a>

— void(0) — отмена пересылки данных на сервер
— при нажатии на ссылку происходит переход к выполнению action

Событие javascript onsubmit и onreset

Рассмотрим использование событий на примерах:

Пример: Перед отправкой формы на сервер необходимо отобразить простое сообщение для пользователя с просьбой подтвердить заполнение формы заказа

function confirmOrder() { confirm ('Вы подтверждаете заказ?') ; }
 form action="script.php" method="post" onsubmit="confirmOrder()"> input type="submit" value="ok" /> /form>

В следующем примере происходит регистрация функции-обработчика в качестве свойства элемента:

Пример: При очистке формы (элемент reset ) выдавать диалоговое окно для подтверждения очистки. Выполнить в виде скрипта с ссылкой на функцию

form action="process.cgi" id="f1" method="post"> input type="text" value="John" /> input type="reset" value="cancel" /> /form>
document.getElementById("f1").onreset=function() { confirm ('Вы уверены, что хотите очистить форму?') ; };

В скрипте происходит обращение к форме ( f1 ) и в качестве ее свойства указывается функция-обработчик

Задание js9_1. Создать страницу с текстовым полем и двумя кнопками. При нажатии одной из них происходит передача данных содержимого текстового поля по электронной почте ( action=»mailto:address@domen.domen» ), при нажатии другой – происходит очистка текстового поля

Задание js9_2. По щелчку на кнопке очистки формы устанавливать надпись «Готово!» на этой кнопке (свойство value )

Источник

Читайте также:  Bootstrap Example
Оцените статью