Очень долго выдумывал какое дать название этой статье и ничего лучшего не смог придумать. Это единственное название, которое хоть как-то отражает суть изложенного. Я, если честно, не знаю как правильно это называется, поэтому назвал статью также, как пытался найти хоть какую-то информацию в поисковике по этой теме.

На одном из сайтов мне потребовалось в одной форме использовать две кнопки submit , которые пересылали бы заполненные данные разным PHP -“обработчикам”, в зависимости от нажатия кнопки. Google ничего вменяемого мне не ответил, видимо я просто не так его как-то об этом просил, поэтому пришлось придумывать самому.

Вот и выложил на Ваш суд.

Суть проблемы

После самостоятельной реализации, я все таки нашел несколько решения, которые основывались на использовании обычных кнопок, к которым прикручивался JS.

Я реализовал задуманное практически также, но использовал стандартный тип submit. Все вроде работает и на мой взгляд мое решение более логически верное.

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

Для того, чтобы было более проще понять что я хочу и как это работает вот реально рабочий пример, в виде формы, у который 2 submit`a, пересылающие данные на разные страницы.

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 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

есть ли способ сделать выбор группы опций?

Child Tag Child Tag

7 54

Keavon

7 ответов:

до тех пор, пока это не поддерживается в стандарте html, любые и все ответы были проблематичными, в том числе:

  • атрибуты класса для детей выбрать, а если как стиль применяется к элементу, варьируются в зависимости от браузера и его версии.
  • префикс с будет иметь следствием, что если выбрать элемент уже, чем выбранный вариант, визуальный эффект не будет приятным, с читаемым текстом скрыт справа (см. пример ниже).
  • любой стиль, который вы применяете, не обязательно будет соответствовать стилю, к которому привык пользователь браузера. жирный шрифт и курсив-это Firefox, но не обязательно каждый браузер. Многие браузеры применяют стиль, включая серый цвет, чтобы помочь указать, что optgroup не выбирается
  • концепция метки select optgroup не обязательно будет ожидаться пользователем.
  • Это привело меня к выводу лучше способ обойти эту проблему-либо использовать библиотеку, такую как 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"; }

    Цель:
    Сегодня наша задача замена стандартной кнопки «отправить» на красивую. Кнопка выполняет отправку формы и имеет тип «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;

    Этот вопрос входит, наверное, в ТОП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; чтобы текст кнопки можно было выделять, но я сомневаюсь в такой надобности.

    Остальные стили будут уже зависеть от конкретного дизайна.

    Несколько примечаний:

  • К кнопке не удастся применить псевдоклассы active, visited, а для IE6 и hover
  • В IE6 не будут нормально работать несколько button для одной формы
  • Без JS можно обойтись. Все зависит от того, насколько вам важна естественность ссылки
  • UPD
    insa , не кроссбраузерный (читайте комментарии).