HTML-формы. Странное поведение html form submit Что значит submit в html
есть ли способ сделать выбор группы опций?
Child Tag Child Tag
7 54Keavon
7 ответов:до тех пор, пока это не поддерживается в стандарте html, любые и все ответы были проблематичными, в том числе:
Это привело меня к выводу лучше способ обойти эту проблему-либо использовать библиотеку, такую как UI-Selectable for all selects на вашем сайте (для согласованности), либо использовать первый вариант в optgroup для представления выбора всех детей с четким описанием (например, "все шведские автомобили"):
ALL Children Child Tag 1 Child Tag 2 .my-select { width: 60px; } Parent Child
немного другое решение..
OptionGroup { font-weight: bold; } Parent Tag Child Tag1 Child Tag2
ответ@grifos не поддерживается в браузерах WebKit и не работает при тестировании в IE 11.
одним из предложений может быть использование неупорядоченного/упорядоченного списка и стиль его с помощью CSS, а затем добавить функциональность с помощью JavaScript/jQuery.
Я видел хорошую реализацию этого в прошлом, это может выглядеть очень гладко!
это даст голое ощущение выпадающего списка с возможностью выбора optgroups. Оставил его очень простым, но вы можете стиль для вашего сердца содержание.
Hide { display:none; } .show { display:block; } .selected.button { display:block; font-weight: bold; } button { text-align: left; min-width: 200px; margin-left: 10px; border: 0px; background: #eee; display: block; } #value_display { width: 210px; border: 1px solid #ddd; border-radius: 4px; padding-left: 8px; } opt 0 opt 0 opt 0-1 opt 0-2 opt 0-3 opt 0-4 opt 1 opt 1-1 opt 1-2 opt 1-3 opt 1-4 var showingOptions = false; var showingID = document.getElementById("value_display").innerHTML; function showOptions() { if(showingOptions) { document.getElementById("select_div").className = "hide"; showingOptions = false; } else { document.getElementById("select_div").className = "show"; showingOptions = true; } } function select(id){ document.getElementById(id).className = "selected button"; document.getElementById(showingID).className = "show"; showingID = id; document.getElementById("value_display").innerHTML = id; document.getElementById("select_div").className = "hide"; }
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.
formmethodA 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.
formnovalidateA 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.
formtargetA 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 buttonsbuttons 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 buttonWe"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 shortcutKeyboard 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 buttonTo 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 .
ValidationSubmit buttons don"t participate in constraint validation; they have no real value to be constrained.
ExamplesWe"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."
SpecificationsHTML Living Standard The definition of "" in that specification. |
Living Standard | |
HTML5 The definition of "" in that specification. |
Recommendation |
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 | ||
Chrome Full support 1 | Edge Full support Yes | Firefox Full support 1 |
Зачастую на 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
Как видно, второй пример с циклом, более компактный. Думаю, не стоит приводить скрипт обработчика данной формы, потому что он обрабатывается точно так же как текстовое поле, т.е. значения списка можно извлечь из суперглобального массива $_POST .
Описание:
Создадим HTML-форму для отправки файла на сервер.
В данной html-форме присутствует элемент browse , который открывает диалоговое окно для выбора файла для загрузки на сервер. При нажатии на кнопку "Передать файл" , файл передается сценарию-обработчику.
Затем необходимо написать сценарий обработчик action.php . Перед написание обработчика необходимо определиться в какой каталог мы будет копировать файл:
Замечание
Если вы доверяете пользователям закачивать на ваш сервер любые файлы, нужно быть предельно осторожным. Злоумышленники могут внедрить «нехороший» код в картинку или файл и отправить на сервер. В таких случаях нужно жестоко контролировать загрузку файлов.
Данный пример демонстрирует создание каталога и копирование файла в этот каталог на сервер.
Также хотел бы продемонстрировать пример с элементом checkbox . Этот элемент немного отличается от других элементов тем, что если не один из элементов checkbox ’a не выбран, то суперглобальная переменная $_POST вернет пустое значение:
Синий
Черный
Белый
Очень долго выдумывал какое дать название этой статье и ничего лучшего не смог придумать. Это единственное название, которое хоть как-то отражает суть изложенного. Я, если честно, не знаю как правильно это называется, поэтому назвал статью также, как пытался найти хоть какую-то информацию в поисковике по этой теме.
На одном из сайтов мне потребовалось в одной форме использовать две кнопки submit , которые пересылали бы заполненные данные разным PHP -“обработчикам”, в зависимости от нажатия кнопки. Google ничего вменяемого мне не ответил, видимо я просто не так его как-то об этом просил, поэтому пришлось придумывать самому.
Вот и выложил на Ваш суд.
Суть проблемыПосле самостоятельной реализации, я все таки нашел несколько решения, которые основывались на использовании обычных кнопок, к которым прикручивался JS.
Я реализовал задуманное практически также, но использовал стандартный тип submit. Все вроде работает и на мой взгляд мое решение более логически верное.
Это решение будет одинаково хорошо работать как на бесплатном хостинге, так и в том случае, если Вы выберите профессиональный хостинг . Данный способ реализуется полностью на стороне клиента и не должен тормозить работу сервера.
Для того, чтобы было более проще понять что я хочу и как это работает вот реально рабочий пример, в виде формы, у который 2 submit`a, пересылающие данные на разные страницы.
Этот вопрос входит, наверное, в ТОП10 вопросов на форумах:) Скорей всего это требование дизайнера или заказчика.
Итак, решение, на первый взгляд, простое:
ОтправитьНо тут же возникает (как ни странно:) следующий вопрос это, а если JS будет у посетителя отключен?
Изменим наш код на:
И добавим немного JS:
addEvent(window, "load" , windowLoad) ;/* Кроссбраузерное добавление обработчика события */
function
addEvent(obj,
evType,
fn)
{
if
(obj.addEventListener
)
{
obj.addEventListener
(evType,
fn,
false
)
;
}
else
if
(obj.attachEvent
)
{
obj.attachEvent
("on"
+
evType,
fn)
;
}
}
/* Получаем родительскую форму для элемента */
function
getParentForm(obj)
{
while
((obj =
obj.parentNode
)
)
{
if
(obj.nodeName
==
"FORM"
)
{
break
;
}
}
return
obj;
}
/* Ищем все submit-кнопки с классом link и заменяем их на ссылки */
function
windowLoad()
{
var
buttons =
document.getElementsByTagName
("input"
)
;
for
(var
i =
0;
i <
buttons.length
;
i++
)
{
link.appendChild
(document.createTextNode
(buttons[
i]
.getAttribute
("value"
)
)
)
;
link.setAttribute
("href"
,
"#"
)
;
addEvent(link,
"click"
,
linkClick)
;
var
parent =
buttons[
i]
.parentNode
;
parent.removeChild
(buttons[
i]
)
;
parent.appendChild
(link)
;
}
}
}
/* Отправляем форму по нажатию на ссылку */
function
linkClick(e)
{
var
e =
window.event
||
e;
var
target =
e.target
||
e.srcElement
;
var
parentForm =
getParentForm(target)
;
parentForm.submit
()
;
if
(window.event
)
{
e.returnValue
=
false
;
}
else
{
e.preventDefault
()
;
}
}
Теперь, если JS будет отключен, посетитель увидит вместо ссылки кнопку и все равно сможет отправить форму. Но мы на этом не остановимся. Заставим кнопку выглядеть как ссылка даже если отключен JS. Для того чтобы стилизировать кнопку изменим тег на button , а span нужен для того чтобы можно было в Firefox добавить подчеркивание текста.
ОтправитьТакже изменим соответственно часть JS.
var buttons = document.getElementsByTagName ("button" ) ;for (var i = 0; i < buttons.length ; i++ ) {
if (buttons[ i] .getAttribute ("type" ) == "submit" && buttons[ i] .className == "link" ) {
var link = document.createElement ("a" ) ;
link.appendChild (document.createTextNode (buttons[ i] .firstChild .firstChild .nodeValue ) ) ;
CSS будет выглядеть следующим образом:
button.link {/* Первые два свойства нужны чтобы убрать отступы в IE */
overflow : visible ;
width : auto ;
/* Убираем отступы */
margin
:
0;
padding
:
0;
/* Убираем все элементы оформления кнопки */
background
:
none
;
border
:
none
;
/* Обычный для ссылок курсор */
cursor
:
pointer
;
}
/* Ссылка обычно подчеркнута */
button.link
span {
color
:
#00f
;
text-decoration
:
underline
;
}
Для Firefox можно еще добавить -moz-user-select: text; чтобы текст кнопки можно было выделять, но я сомневаюсь в такой надобности.
Остальные стили будут уже зависеть от конкретного дизайна.
Несколько примечаний:
UPD
insa , не кроссбраузерный (читайте комментарии).