Как изменить текст input submit

I have a tag, . I want to have the text inside the button say "Like", but right now, it says "Submit". class="like" is the CSS of the button, by the way.

I have a tag, <input type="submit" class="like"/>.
I want to have the text inside the button say «Like», but right now, it says «Submit».

class="like" is the CSS of the button, by the way.

Joey M's user avatar

Joey M

1761 silver badge14 bronze badges

asked Dec 22, 2012 at 23:59

user1261817's user avatar

The value attribute on submit-type <input> elements controls the text displayed.

<input type="submit" class="like" value="Like" />

answered Dec 23, 2012 at 0:00

Ry-'s user avatar

Ry-Ry-

215k54 gold badges456 silver badges466 bronze badges

2

The value attribute is used to determine the rendered label of a submit input.

<input type="submit" class="like" value="Like" />

Note that if the control is successful (this one won’t be as it has no name) this will also be the submitted value for it.

To have a different submitted value and label you need to use a button element, in which the textNode inside the element determines the label. You can include other elements (including <img> here).

<button type="submit" class="like" name="foo" value="bar">Like</button>

Note that support for <button> is dodgy in older versions of Internet Explorer.

answered Dec 23, 2012 at 0:00

Quentin's user avatar

QuentinQuentin

893k122 gold badges1194 silver badges1316 bronze badges

<input name="submitBnt" type="submit" value="like"/>

name is useful when using $_POST in php and also in javascript as document.getElementByName('submitBnt').
Also you can use name as a CS selector like input[name="submitBnt"];
Hope this helps

answered Dec 23, 2012 at 0:01

bashleigh's user avatar

bashleighbashleigh

8,4745 gold badges27 silver badges48 bronze badges

Цитата
Сообщение от sashgera
Посмотреть сообщение

я вам показал полностью свой php обработчик формы, (работоспособный)

вы можете представить себе: у меня на этом компе нет

швейной машинки

виртуального сервера с PHP-интерпретатором
я не могу запустить ваш PHP-код в своём браузере. чтобы посмотреть — чего и как там устроено
и что мне делать?
думаете, я один такой — без Денвера на компе?
уверяю вас — вы ошибаетесь… очень многие даже не знают, что это такое
————

ну да ладно — выслали ссылку, вопрос снимается

1. начну с того, что я совершенно не понимаю — зачем вам постоянно рефрешить страницу?
имеется у вас на странице форма, заполнил её клиент, нажал «отправить», страница один раз перегрузилась, выдав какой-то из вариантов («ошибка заполнения формы», «успешная отправка»)
всё, ничего более от страницы не требуется

итак, зачем рефрешить?
какая «умная голова» это придумала?
или ваша зарплата напрямую зависит от нагрузки на сервер?
с моей точки зрения этот ваш «рефрешный вариант» — полная и беспросветная глупость

рефрешат страницу в исключительных случаях — когда необходимо постоянно отслеживать изменения данных на сервере и отображать эти изменения в режиме реального времени

2. обычная форма при нормальном интернет-соединении НЕ ТРЕБУЕТ никаких наворотов при сабмите,
потому что страница сразу перезагружается на результат — т.е. на то, что указано в атрибуте ACTION тега <FORM>

зайдите для примера на httр://google.com или на

httр://yandex.ru — там же тоже формы
когда вы там жмёте на кнопку «Искать», надпись на кнопке разве меняется на «Подождите, мы ищем»?
нет, не меняется
ибо это — полный маразм, никому не нужный
в Гугле и Яндексе это понимают
вы же явно полагаете себя умнее всех, потому такую фигню и придумали

3. какие-либо предупреждающе надписи («Подождите», «Идёт загрузка») имеют право на жизнь
и их много где применяют
но применяют их в тех случаях, когда страница НЕ перегружается вовсе, а когда используется технология получения данных БЕЗ ПЕРЕЗАГРУЗКИ, т.е. через объект XMLHTTPRequest (чаще всего в асинхронном варианте, называемом AJAX’ом)

нажал в этом случае пользователь кнопку — запрос ушёл на сервер, а на странице появляется надпись «Ждите»
когда пришел ответ с сервера, надпись снимается и часть страницы изменяется (добавляется ответ сервера)

делается это исключительно для того, чтобы показать юзеру, что его запрос начал исполняться, ведь страница та же, надо показать, что страница «живёт»

у вас же — полный бред, на страницу, которая регулярно обновляется, вы хотите навесить ещё и предупреждающую надпись… полный идиотизм, в общем…
————

ну да ладно, если у вас нет более проблем, кроме как создавать идиотские страницы в сети, подсказываю:

HTML5
1
2
3
4
5
6
<input type="button"
       value="Отправить"
       onclick="this.value = 'Подождите';
                this.disabled = true;
                MFRM = this.form;
                setTimeout ('MFRM.submit ()', 6000)">

In the example below, we have <input> elements with type="button" and type="submit", which we style with CSS properties. To style them, we use the background-color and color properties, set the border and text-decoration properties to «none». Then, we add padding and margin, after which we specify the cursor as «pointer».

Example of styling the input and submit buttons:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      input[type=button],
      input[type=submit] {
        background-color: #62529c;
        border: none;
        color: #fff;
        padding: 15px 30px;
        text-decoration: none;
        margin: 4px 2px;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <p>Styled input buttons.</p>
    <input type="button" value="Button">
    <input type="submit" value="Submit">
  </body>
</html>

Result

In the next example, we have a <form> element within which we add <div> elements each containing a <label> and <input>. Then, we add another <input> with type="submit" and style it.

Example of styling a submit button in a form:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      div {
        margin-bottom: 10px;
      }
      input[type=text] {
        padding: 5px;
        border: 2px solid #cccccc;
        -webkit-border-radius: 5px;
        border-radius: 5px;
      }
      input[type=text]:focus {
        border-color: #33333;
      }
      input[type=submit] {
        padding: 5px 15px;
        background: #99e0b2;
        border: 0 none;
        cursor: pointer;
        -webkit-border-radius: 5px;
        border-radius: 5px;
      }
    </style>
  </head>
  <body>
    <h2>Form example</h2>
    <form action="/form/submit" method="POST">
      <div>
        <label for="surname">Surname</label>
        <input type="text" name="surname" id="surname" placeholder="surname" />
      </div>
      <div>
        <label for="lastname">Last name</label>
        <input type="text" name="lastname" id="lastname" placeholder="lastname" />
      </div>
      <div>
        <label for="email">Email</label>
        <input type="email" name="email" id="email" placeholder="email" />
      </div>
      <input type="submit" value="Submit" />
    </form>
  </body>
</html>

В этом посте мы обсудим, как изменить значение <input> элемент типа button или submit в JavaScript и jQuery.

С помощью jQuery вы можете использовать .val() метод для установки значений элементов формы. Чтобы изменить значение <input> элементы типа button или типа submit (т.е. <input type="button"> или же <input type="submit">), вы можете сделать так:

JS

$(document).ready(function() {

    $(‘#submit’).click(function() {

        $(this).val(‘Processing…’);

    })

});

HTML

<!doctype html>

<html lang=«en»>

<body>

    <input type=«button» id=«submit» value=«Submit» class=«btn»>

</body>

</html>

CSS

.btn {

    font-size: 14px;

    margin: 8px;

    padding: 0 15px;

}

Изменить в JSFiddle

 
В качестве альтернативы вы можете использовать jQuery .prop() метод.

JS

$(document).ready(function() {

    $(‘#submit’).click(function() {

        $(this).prop(‘value’, ‘Processing…’);

    })

});

HTML

<!doctype html>

<html lang=«en»>

<body>

    <input type=«button» id=«submit» value=«Submit» class=«btn»>

</body>

</html>

CSS

.btn {

    font-size: 14px;

    margin: 8px;

    padding: 0 15px;

}

Изменить в JSFiddle

2. Использование JavaScript

С помощью JavaScript вы можете изменить <input> атрибут value элементов, который содержит DOMString используется в качестве метки кнопки.

JS

document.getElementById(‘submit’).onclick = function() {

    this.value = ‘Processing…’;

}

HTML

<!doctype html>

<html lang=«en»>

<body>

    <input type=«button» id=«submit» value=«Submit» class=«btn»>

</body>

</html>

CSS

.btn {

    font-size: 14px;

    margin: 8px;

    padding: 0 15px;

}

Изменить в JSFiddle

Вот и все, что касается изменения значения кнопки в JavaScript и jQuery.

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

<input> elements of type submit are rendered as buttons. When the click event occurs (typically because the user clicked the button), the user agent attempts to submit the form to the server.

Value

An <input type="submit"> element’s value attribute contains a string which is displayed as the button’s label. Buttons do not have a true value otherwise.

Setting the value attribute

<input type="submit" value="Send Request" />

Omitting the value attribute

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

In addition to the attributes shared by all <input> elements, submit button inputs support the following attributes.

formaction

A string indicating the URL to which to submit the data. This takes precedence over the action attribute on the <form> element that owns the <input>.

This attribute is also available on <input type="image"> and <button> elements.

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 encodeURI().

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 <input> elements of type file (<input 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.

This attribute is also available on <input type="image"> and <button> elements.

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 get 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 method. This method supports complex data and file attachments.

dialog

This method is used to indicate that the button closes the dialog with which the input is associated, and does not transmit the form data at all.

This attribute is also available on <input type="image"> and <button> elements.

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.

This attribute is also available on <input type="image"> and <button> elements.

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 <iframe>). A value specified here overrides any target given by the target attribute on the <form> 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.

This attribute is also available on <input type="image"> and <button> elements.

Using submit buttons

<input type="submit"> 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 <input type="button">, or better still, a <button> element.

If you choose to use <button> elements to create the buttons in your form, keep this in mind: If the <button> is inside a <form>, 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:

<form>
  <div>
    <label for="example">Let's submit some text</label>
    <input id="example" type="text" name="text" />
  </div>
  <div>
    <input type="submit" value="Send" />
  </div>
</form>

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 <form>; see Sending form data for more details.

Adding a keyboard shortcut to a submit button

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

<form>
  <div>
    <label for="example">Let's submit some text</label>
    <input id="example" type="text" name="text" />
  </div>
  <div>
    <input type="submit" value="Send" accesskey="s" />
  </div>
</form>

For example, in Firefox for Mac, pressing ControlOptionS 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, specify the disabled attribute on it, like so:

<input type="submit" value="Send" disabled />

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

Note: See the <input type="button"> page for more ideas about enabling and disabling buttons.

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

Technical Summary

Value A string used as the button’s label
Events click
Supported common attributes type and
value
IDL attributes value
DOM interface

HTMLInputElement

Methods None
Implicit ARIA Role button

Specifications

Specification
HTML Standard
# submit-button-state-(type=submit)

Browser compatibility

BCD tables only load in the browser

See also

19th March 2010 — 3 minutes read time

Changing the text of a submit button when clicked can be useful if you are writing an AJAX application or you know that there will be some sort of delay. Providing the user with some form of feedback is a useful way of letting them know they they have done something.

First, we need a form to work with, so I built a quick one here. Notice that the submit button has an onclick action associated with it, this will be used later to enable us to alter the text of the button.

<form action="" method="get">
<label for="textinput">Text:</label> <input id="textinput" name="textinput" type="text" value="" /> <input id="submitbutton" onclick="return changeText('submitbutton');" type="submit" value="Search" />&nbsp;
</form>

The following JavaScript block defines the function that changes the text of the submit button. The function just looks up the input element and changes the value of it to «Loading…». This function returns false, which causes the button not to submit the form. This can be changed to true if you want the form to be submitted when the button is pressed.

<script type="text/javascript"> 
    function changeText(submitId){
        var submit = document.getElementById(submitId);
        submit.value = 'Loading...';
        return false;
    };
</script>

Related Content

Creating A Simple Pie Chart With CSS

25th December 2022

A pie chart is a great way of showing the relationship between numbers, especially when showing percentages. Drawing a pie chart from scratch takes a fair amount of maths to get working and so people usually go for third party charting libraries in order to add charts to the page.

Read more

Getting Up And Running With Nightwatch.js

24th July 2022

Nightwatch.js is an end to end testing framework, written in JavaScript. It can be used to test websites and applications and uses the W3C WebDriver API to drive modern browsers to perform the tests.

In this article I will look at setting up Nightwatch.js in a project and getting started with writing tests.

Read more

Creating Presentations In Markdown With Marp

15th May 2022

Marp or Markdown Presentation Ecosystem is a collection of tools that allows the generation of presentations of different formats from a markdown template. The tools are written in JavaScript and have a number of options that allow presentations of different styles and formats.

Read more

Creating A Reading Progress Bar In JavaScript

9th January 2022

Adding a progress bar to the top of the page is a simple way of showing the user how far down the page they have read. There is a scroll bar on the right hand side of the page on my current device, but that isn’t always present on all devices.

Read more

Animating Number Updates With jQuery

5th December 2021

I was working on a user dashboard recently and decided to add some more signposting to values being updated.  Users were able to select different parameters in order to produce different values, but I thought that the values being updated weren’t clear enough.

Read more

Понравилась статья? Поделить с друзьями:
  • Как изменить текст на клавиатуре на телефоне
  • Как изменить текст footer joomla
  • Как изменить текст canvas tkinter
  • Как изменить текст на кириллицу
  • Как изменить текст на картинке через фотошоп