Энциклопедия мобильной связи

Множественные submit для формы. Странное поведение html form submit

Зачастую на Web – сайтах можно встретить страницы с размещенными на них HTML - формами. Веб-формы – удобный способ получения информации от посетителей вашего сайта. Пример тому – , – которая обеспечивает обратную связь с посетителями и разработчиками сайта. Формы так же удобны и для разработчиков сайта при разработке CMS, которая позволяет поддерживать главное свойство сайта - актуальность. Данная статья посвящена основам создания HTML-форм, их обработке и способам передачи данных из экранных форм в PHP-сценарии.

1) Создание простой формы

Теги и задают начало и конец формы. Начинающий форму тег содержит два атрибута: action и method . Атрибут action содержит адрес URL сценария, который должен быть вызван для обработки сценария. Атрибут method указывает браузеру, какой вид HTTP запроса необходимо использовать для отправки формы; возможны значения POST и GET .

Замечание

Главное отличие методов POST и GET заключается в способе передачи информации. В методе GET параметры передаются через адресную строку, т.е. по сути в HTTP-заголовке запроса, в то время как в методе POST параметры передаются через тело HTTP-запроса и никак не отражаются на виде адресной строки.

Задача: Пусть необходимо создать выпадающий список с годами с 2000 по 2050.
Решение: Необходимо создать HTML форму c элементом SELECT и PHP – сценарий для обработки формы.

Обсуждение:

Для начала создадим два файла: form.html и action.php . В файле form.html будет содержаться html-форма с выпадающим списком. Причем значения в списке можно указать двумя способами:

I. Ввод данных вручную:


2000
2001
2002
……………………………………………
2050

II. Ввод данных через цикл:



Как видно, второй пример с циклом, более компактный. Думаю, не стоит приводить скрипт обработчика данной формы, потому что он обрабатывается точно так же как текстовое поле, т.е. значения списка можно извлечь из суперглобального массива $_POST .

Описание:

Создадим HTML-форму для отправки файла на сервер.




В данной html-форме присутствует элемент browse , который открывает диалоговое окно для выбора файла для загрузки на сервер. При нажатии на кнопку "Передать файл" , файл передается сценарию-обработчику.

Затем необходимо написать сценарий обработчик action.php . Перед написание обработчика необходимо определиться в какой каталог мы будет копировать файл:

Замечание

Если вы доверяете пользователям закачивать на ваш сервер любые файлы, нужно быть предельно осторожным. Злоумышленники могут внедрить «нехороший» код в картинку или файл и отправить на сервер. В таких случаях нужно жестоко контролировать загрузку файлов.

Данный пример демонстрирует создание каталога и копирование файла в этот каталог на сервер.

Также хотел бы продемонстрировать пример с элементом checkbox . Этот элемент немного отличается от других элементов тем, что если не один из элементов checkbox ’a не выбран, то суперглобальная переменная $_POST вернет пустое значение:


Синий
Черный
Белый

На днях мне понадобилось реализовать отправку данных формы на сервер (submit формы), но с предварительной обработкой события формы onsubmit . Все бы ничего, если бы это можно было бы сделать при обычном нажатии на кнопку submit , но задача была немного усложнена тем, что сабмитить форму надо было автоматически, а не по запросу пользователя. В моем случае — по таймеру.

Естественно, при отправке данных на сервер, необходимо было воспользоваться JavaScript методом form.submit () . Каково же было мое удивление, когда я обнаружил, что метод отправки данных с помощью кнопки submit и работа JavaScript метода формы submit () кардинально отличаются.

Для того чтобы наглядно продемонстрировать поведение данных методов, я приведу их исходники и примеры работы.

Пример отправки данных на сервер (post) с помощью обычной кнопки и предварительная обработка onsubmit будет выглядеть так:

Отправить

при таком коде HTML, поведение формы будет следующим: если нажать кнопку «Отправить», сначала выскочит окошко с предупреждением об отправке данных на сервер, а после нажатия на кнопку «ОК», данные будут отправлены на сервер.

А что же будет, если заменить кнопку submit на JavaScript метод form.submit () ?

Отправить

а вот в этом случае, и произойдет то самое, странное поведение формы — событие onsubmit не сработает, но данные будут отправлены на сервер.

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

А что же по этому поводу говорит спецификация W3C и основные производители браузеров.

У Microsoft более лаконичное описание, «The submit method does not invoke the onsubmit event handler.» (Метод submit не вызывает событие onsubmit ).

Как же выйти из этой ситуации?

Одним из решений может быть создание невидимой кнопки submit и вызов ее метода click () . Но это не сильно красивое решение. Поэтому можно подключить библиотеку jQuery и написать несколько строк кода на JavaScript для программной генерации событий.

$.fn.fireEvent = function(eventType) { return this.each(function() { if (document.createEvent) { var event = document.createEvent("HTMLEvents"); event.initEvent(eventType, true, true); return !this.dispatchEvent(event); } else { var event = document.createEventObject(); return this.fireEvent("on" + eventType, event) } }); };

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

$("myform").fireEvent("submit");

На просторах сети, я находил еще одно решение — это использование метода trigger () , вместо метода fireEvent () , только он тоже не работает так как надо, потому и не буду его приводить тут.

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

Attribute contains a DOMString which is displayed as the button"s label. Buttons do not have a true value otherwise.

If you don"t specify a value , the button will have a default label, chosen by the user agent. This label is likely to be something along the lines of "Submit" or "Submit Query." Here"s an example of a submit button with a default label in your browser:

Additional attributes formenctype

A string that identifies the encoding method to use when submitting the form data to the server. There are three permitted values:

Application/x-www-form-urlencoded This, the default value, sends the form data as a string after URL encoding the text using an algorithm such as . multipart/form-data Uses the FormData API to manage the data, allowing for files to be submitted to the server. You must use this encoding type if your form includes any elements of type file (). text/plain Plain text; mostly useful only for debugging, so you can easily see the data that"s to be submitted.

If specified, the value of the formenctype attribute overrides the owning form"s action attribute.

formmethod

A string indicating the HTTP method to use when submitting the form"s data; this value overrides any method attribute given on the owning form. Permitted values are:

Get A URL is constructed by starting with the URL given by the formaction or action attribute, appending a question mark ("?") character, then appending the form"s data, encoded as described by formenctype or the form"s enctype attribute. This URL is then sent to the server using an HTTP request. This method works well for simple forms that contain only ASCII characters and have no side effects. This is the default value. post The form"s data is included in the body of the request that is sent to the URL given by the formaction or action attribute using an HTTP post request. This method supports complex data and file attachments. dialog This method is used to indicate that the button simply closes the dialog with which the input is associated, and does not transmit the form data at all.

formnovalidate

A Boolean attribute which, if present, specifies that the form should not be validated before submission to the server. This overrides the value of the novalidate attribute on the element"s owning form.

formtarget

A string which specifies a name or keyword that indicates where to display the response received after submitting the form. The string must be the name of a browsing context (that is, a tab, window, or . A value specified here overrides any target given by the target attribute on the that owns this input.

In addition to the actual names of tabs, windows, or inline frames, there are a few special keywords that can be used:

Self Loads the response into the same browsing context as the one that contains the form. This will replace the current document with the received data. This is the default value used if none is specified. _blank Loads the response into a new, unnamed, browsing context. This is typically a new tab in the same window as the current document, but may differ depending on the configuration of the user agent . _parent Loads the response into the parent browsing context of the current one. If there is no parent context, this behaves the same as _self . _top Loads the response into the top-level browsing context; this is the browsing context that is the topmost ancestor of the current context. If the current context is the topmost context, this behaves the same as _self .

Using submit buttons

buttons are used to submit forms. If you want to create a custom button and then customize the behavior using JavaScript, you need to use , or better still, a element.

If you choose to use elements to create the buttons in your form, keep this in mind: if there"s only one inside the , that button will be treated as the "submit" button. So you should be in the habit of expressly specifying which button is the submit button.

A simple submit button

We"ll begin by creating a form with a simple submit button:

Let"s submit some text

This renders like so:

Try entering some text into the text field, and then submitting the form.

Upon submitting, the data name/value pair gets sent to the server. In this instance, the string will be text=usertext , where "usertext" is the text entered by the user, encoded to preserve special characters. Where and how the data is submitted depends on the configuration of the ; see Sending form data for more details.

Adding a submit keyboard shortcut

Keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard. To add a keyboard shortcut to a submit button - just as you would with any for which it makes sense - you use the accesskey global attribute.

In this example, s is specified as the access key (you"ll need to press s plus the particular modifier keys for your browser/OS combination. In order to avoid conflicts with the user agent"s own keyboard shortcuts, different modifier keys are used for access keys than for other shortcuts on the host computer. See accesskey for further details.

Here"s the previous example with the s access key added:

Let"s submit some text

For example, in Firefox for Mac, pressing Control - Option - S triggers the Send button, while Chrome on Windows uses Alt + S .

The problem with the above example is that the user will not know what the access key is! This is especially true since the modifiers are typically non-standard to avoid conflicts. When building a site, be sure to provide this information in a way that doesn"t interfere with the site design (for example by providing an easily accessible link that points to information on what the site access keys are). Adding a tooltip to the button (using the title attribute) can also help, although it"s not a complete solution for accessibility purposes.

Disabling and enabling a submit button

To disable a submit button, simply specify the disabled global attribute on it, like so:

You can enable and disable buttons at run time by simply setting disabled to true or false ; in JavaScript this looks like btn.disabled = true or btn.disabled = false .

Validation

Submit buttons don"t participate in constraint validation; they have no real value to be constrained.

Examples

We"ve included simple examples above. There isn"t really anything more to say about submit buttons. There"s a reason this kind of control is sometimes called a "simple button."

Specifications Specification Status Comments
HTML Living Standard
The definition of "" in that specification.
Living Standard
HTML5
The definition of "" in that specification.
Recommendation
Browser compatibility

The compatibility table on this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Desktop Mobile Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Edge Mobile Firefox for Android Opera for Android Safari on iOS Samsung Internet type="submit"
Chrome Full support 1 Edge Full support Yes Firefox Full support 1

Цель:
Сегодня наша задача замена стандартной кнопки «отправить» на красивую. Кнопка выполняет отправку формы и имеет тип «submit». Можно конечно изменить тип с «submit» на «image» и добавить параметр «src», но наша задача на сегодня это оставить тип «submit» на месте и программно нарисовать красивую кнопку.

Применение:
Для чего это может понадобиться? Всё просто, для придания эстетичного вида той самой кнопке.
Вот для сравнения. Наглядно видно, что вторая кнопка смотрится лучше.

Решение:
Для выполнения данной цели как и говорилось мы будем применять «input» с типом «submit». Ещё нам понадобится описать новый класс в таблице стилей «*.css»
Вот код для html-файла:

А вот и css:

Superbutton {
width:150px;
height:40px;
border-radius:20px;
background:#459DE5;
color:#fff;
font-size:18px;
cursor:pointer;
}

Украшаем:
Для украшения можно предложить изменять цвет фона кнопки при наведении. Как правило дизайнеры советуют менять цвет не кардинально, а всего лишь на тон светлее или темнее. Я при выполнении задачи предпочел затемнить кнопку. Для этого в css добавляем:

Superbutton:hover{
background:#358DE5;
}

Теперь кнопка ожила. На статичной картинке разность цветов не так заметна когда ты наводишь мышь и цвет в туже секунду меняется накладывая более темный оттенок.

Проблема рамки вокруг кнопки:
И всё вроде ничего и выглядит ничего и при наведении темнеет, но при нажатии мы видим ужасную рамку. Ещё эту рамку можно наблюдать если наша кнопка находится в фокусе, в том который по кнопке Tab перебирает элементы на странице.
Для этого мы пропишем в css ещё 2 псевдо класса, как и «hover». Это классы «active» который отвечает за вид при нажатии на кнопку и класс «focus» при фокусе на кнопке. Но есть одна особенность, так как у нас input и присвоенный ему класс, то active прописывать не обязательно.
Вот код:

Superbutton:focus{
outline:none;



Понравилась статья? Поделитесь с друзьями!
Была ли эта статья полезной?
Да
Нет
Спасибо, за Ваш отзыв!
Что-то пошло не так и Ваш голос не был учтен.
Спасибо. Ваше сообщение отправлено
Нашли в тексте ошибку?
Выделите её, нажмите Ctrl + Enter и мы всё исправим!