Устанавливает обработчик отправки формы на сервер, либо запускает это событие. Метод имеет три варианта использования:
handler(eventObject) — функция, которая будет установлена в качестве обработчика. При вызове она будет получать объект события eventObject .
handler(eventObject)
— см. выше.
eventData
— дополнительные данные, передаваемые в обработчик. Они должны быть представлены объектом в формате: {fName1:value1, fName2:value2, ...} .
Убрать установленный обработчик можно с помощью метода unbind() .
Все три варианта использования метода, являются аналогами других методов (см. выше), поэтому все подробности использования submit() , можно найти в описании этих методов.
Событие submit происходит непосредственно перед отправкой формы на сервер и в обработчике можно инициировать отмену отправки формы, вызвав метод eventObject.preventDefault() или просто возвратив false .
В IE событие submit в отличие от других событий не обладает свойством "всплытия вверх по иерархии". Однако начиная с jQuery-1.4 эта недоработка устранена и обработчики события submit , установленные на элементы, которые лежат выше элемента формы по иерархии, будут оповещены о предстоящей отправке данных на сервер.
Пример
// установим обработчик события submit, элементу с идентификатором foo, // после чего запретим отправку данных на сервер $("#foo" ) .submit (function () { alert ("Форма foo отправлена на сервер." ) ; return false ; } ) ; // вызовем событие submit на элементе foo $("#foo" ) .submit () ; // установим еще один обработчик события submit, на этот раз элементам // с классом block. В обработчик передадим дополнительные данные $(".block" ) .submit ({ a: 12 , b: "abc" } , function (eventObject) { var externalData = "a=" + eventObject.data .a + ", b=" + eventObject.data .b ; alert ("Форма foo отправлена на сервер. " + "В обработчик этого события переданы данные: " + externalData ) ; } ) ;
Цель:
Сегодня наша задача замена стандартной кнопки «отправить» на красивую. Кнопка выполняет отправку формы и имеет тип «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;
Очень долго выдумывал какое дать название этой статье и ничего лучшего не смог придумать. Это единственное название, которое хоть как-то отражает суть изложенного. Я, если честно, не знаю как правильно это называется, поэтому назвал статью также, как пытался найти хоть какую-то информацию в поисковике по этой теме.
На одном из сайтов мне потребовалось в одной форме использовать две кнопки submit , которые пересылали бы заполненные данные разным PHP -“обработчикам”, в зависимости от нажатия кнопки. Google ничего вменяемого мне не ответил, видимо я просто не так его как-то об этом просил, поэтому пришлось придумывать самому.
Вот и выложил на Ваш суд.
Суть проблемы
После самостоятельной реализации, я все таки нашел несколько решения, которые основывались на использовании обычных кнопок, к которым прикручивался JS.
Я реализовал задуманное практически также, но использовал стандартный тип submit. Все вроде работает и на мой взгляд мое решение более логически верное.
Это решение будет одинаково хорошо работать как на бесплатном хостинге, так и в том случае, если Вы выберите профессиональный хостинг . Данный способ реализуется полностью на стороне клиента и не должен тормозить работу сервера.
Для того, чтобы было более проще понять что я хочу и как это работает вот реально рабочий пример, в виде формы, у который 2 submit`a, пересылающие данные на разные страницы.
(обычно, поскольку пользователь нажал кнопку), пользовательский агент пытается отправить форму на сервер.
Стоимость
Если вы решили использовать элементы
Простая кнопка отправки
Начнем с создания формы с простой кнопкой отправки:
Это делает так:
Попробуйте ввести текст в текстовое поле, а затем отправьте форму.
После отправки пары имя / значение данных отправляется на сервер. В этом случае строка будет "text= usertext " , где «usertext» - это текст, введенный пользователем, закодированный для сохранения специальных символов. Где и как данные передаются, зависит от конфигурации
Добавление сочетания клавиш отправки
Ярлыки клавиш, также называемые клавишами доступа и эквивалентами клавиатуры, позволяют пользователю запускать кнопку с помощью клавиши или комбинации клавиш на клавиатуре. Чтобы добавить комбинацию клавиш к кнопке отправки - так же, как и с любым для которого это имеет смысл, вы используете глобальный атрибут accesskey .
В этом примере s указывается как ключ доступа (вам нужно нажать s плюс специальные ключи-модификаторы для вашей комбинации браузера / ОС. Чтобы избежать конфликтов с собственными комбинациями клавиш пользовательского агента, используются разные клавиши-модификаторы для ключи доступа, чем для других ярлыков на главном компьютере. Дополнительные сведения см. в разделе доступа.
Вот предыдущий пример с добавленным ключом доступа s:
Например, в Firefox для Mac нажатие кнопки Control - Option - S вызывает кнопку отправки, в то время как Chrome в Windows использует Alt + S.
Проблема с приведенным выше примером заключается в том, что пользователь не будет знать, что такое ключ доступа! Это особенно верно, поскольку модификаторы обычно нестандартны, чтобы избежать конфликтов. При создании сайта обязательно указывайте эту информацию таким образом, чтобы это не мешало дизайну сайта (например, предоставляя легкодоступную ссылку, указывающую на информацию о том, какие ключи доступа к сайту). Добавление всплывающей подсказки к кнопке (с использованием атрибута title) также может помочь, хотя это не полное решение для целей доступности.
Отключение и включение кнопки отправки
Чтобы отключить кнопку отправки, просто укажите на ней disabled глобальный атрибут, например:
Вы можете включать и отключать кнопки во время выполнения, просто disabled значение true или false ; в JavaScript это выглядит как btn.disabled = true или btn.disabled = false .
Проверка
Кнопки отправки не участвуют в проверке ограничений; они не имеют реальной ценности для ограничения.
Примеры
Мы включили простые примеры выше. Больше нечего сказать о кнопках отправки. Причина такого рода контроля иногда называется «простой кнопкой».
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 element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent."> 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 ) represents a nested browsing context, embedding another HTML page into the current one.">
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
A simple submit button
We"ll begin by creating a form with a simple submit button:
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
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 element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent."> 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:
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 | 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 |