Убрать иконки полей input
Добрый день! Подскажите, как убрать иконки в текстовом поле и в поле пароля при просмотре через Chrome? Все поля текстовые, кроме поля «пароль».
Скрин прилагаю. Стрелками обозначены проблемные поля.
Лучшие ответы ( 1 )
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:
Input text убрать выделение
Как в Input text убрать синие выделение при выделении текста и сделать так чтобы он не выделялся
Убрать мигание коронки в input
Даже не знаю как описать. Есть input поле. При фокусирование на нём появляется | значок.
Убрать полосу вокруг input
Подскажите пожалуйста как можно убрать этот ореол вокруг поля ввода?
Как убрать стрелки и крестик из input type=date
в <input type="date" /> есть справа календарь. В общем надо убрать стрелки и крестик слева. Как это.
2572 / 1664 / 728
Регистрация: 13.03.2010
Сообщений: 5,566
Сообщение было отмечено Отец Олег как решение
Решение
Всего-то нужно изменить пару стилей, скрин прилагаю.
p.s. приведите ссылку на проблемную страницу или приведите код, который позволяет воспроизвести проблему.
Регистрация: 12.12.2014
Сообщений: 184
В этих полях появляются иконки
1 2 3 4 5 6 7 8
tr> td>Имя:/td>td>label>input type="text" class="form-control" name="firstname" pattern="^[А-Яа-я]+$" required />/label> br>code class="warning">small>Только русские символы/small>/code>/td> /tr> tr> td>Пароль:/td>td>label>input type="password" class="form-control" name="password" pattern="" required />/label> br>code class="warning">small>Не менее 8 знаков/small>/code>/td> /tr>
Регистрация: 12.12.2014
Сообщений: 184
Спасибо. Спустя месяц вернулся к этой теме. В итоге сделал так:
1 2 3
#__lpform_password, #__lpform_firstname
Названия ID могут быть у вас иные.
Регистрация: 21.02.2021
Сообщений: 47
Сообщение от Отец Олег
В этих полях появляются иконки
1 2 3 4 5 6 7 8
tr> td>Имя:/td>td>label>input type="text" class="form-control" name="firstname" pattern="^[А-Яа-я]+$" required />/label> br>code class="warning">small>Только русские символы/small>/code>/td> /tr> tr> td>Пароль:/td>td>label>input type="password" class="form-control" name="password" pattern="" required />/label> br>code class="warning">small>Не менее 8 знаков/small>/code>/td> /tr>
Не наблюдаю никаких иконок.
Регистрация: 12.12.2014
Сообщений: 184
С телефона не будет никаких иконок, только хром и ms
Добавлено через 1 минуту
Сообщение от Отец Олег
#__lpform_password, #__lpform_firstname <
visibility: hidden;
>
Забыл добавить в input[type=»text»]
background-image: url('');
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
Помогаю со студенческими работами здесь
Не получается убрать рамку на кнопке INPUT после нажатия
Приветствую! Для отправки формы есть input type="button". Через class прописаны стили. В том числе.
Убрать в input number возможность изменять число стрелками
Сделал input number и появились стрелки при фокусе. Как сделать так, что бы стрелки не появлялись?
Одинаковая ширина для полей input text & input password
Никак не получается выровнять ширину двух тектовых полей: input type=’text’ и input.
Одинаковая ширина для полей input text & input password
Никак не получается выровнять ширину двух тектовых полей: input type=’text’ и input.
Сравнение полей input
Здравствуйте! Как сравнить два поля и выполнить 1. Если они одинаковы: выполнить php скрипт 2.
Как в input[type=»date»] сделать открытие календаря не только с иконки?
Сейчас календарь открывается по нажатию только на иконку
А скрыть дату и иконку, и открывать сам выбор даты по нажатию на любую область input[type=»date»]?
- Вопрос задан более двух лет назад
- 3445 просмотров
6 комментариев
Средний 6 комментариев
Ragtime Kitty @Ragtime_Kitty
Без иконки: https://jsfiddle.net/kwymog96/1/
C иконкой: https://jsfiddle.net/kwymog96/
Ярослав Иванов @space2pacman Куратор тега CSS
Ragtime Kitty, на скриншоте bootstrap. Иконка пропадает.
https://jsfiddle.net/dnv1ucm9/
Ragtime Kitty @Ragtime_Kitty
Ярослав Иванов, так вроде и просили иконку убрать
Хехе, буквально тем же сейчас занимаюсь. Хочу провернуть трюк с type file, но пока не получается.
Грубо говоря сделать обычный div, (например) круг. по клику на который открывается datepicker.
с файлом я делал абсолютное позиционирование и убирал его на -10000px. и стилизовал уже label. По клику на который и открывался выбор файла. с датой пока не получается
Ragtime Kitty Вот такой фокус я с файлами делал. Повырезал лишнего на скорую руку. А так обычный кружок куда фоном фотка подгружается.
а с датой так не получается пока(
Ragtime Kitty @Ragtime_Kitty
Дмитрий, Увы, label для даты не открывает календарь, а каких-либо других способов его тригерить я не вижу 🙁
Как убрать значок календаря у input date
Отображение date различается в зависимости от браузера, кроме того не все браузеры поддерживают date . Подробнее см. Browser compatibility. В неподдерживаемых браузерах элемент будет отображаться как обычный (en-US) .
Интерактивный пример
Среди браузеров со своим интерфейсом для выбора даты, есть интерфейс браузеров Chrome и Opera, который выглядит так:
В Edge он выглядит так:
А в Firefox выглядит так:
Value | Возвращает DOMString , с датой в формате гггг-мм-дд, **или **пустую строку** |
---|---|
События | change (en-US) и input (en-US) |
Поддерживаемые атрибуты | autocomplete , list , readonly , and step |
IDL attributes | list , value , valueAsDate , valueAsNumber . |
Методы | select() (en-US), stepDown() (en-US), stepUp() (en-US) |
Значение
Возвращает DOMString , представляющий значение даты введённой в input. Вы можете установить значение по умолчанию для элемента с помощью добавления атрибута в value , например:
input id="date" type="date" value="2017-06-01" />
Примечание: Помните, что отображаемый формат даты отличается от настоящего значения value – отображаемый формат даты будет выбран, базируясь на региональных параметрах браузера пользователя, тогда как значение value всегда имеет формат гггг-мм-дд .
Вы также можете получить или установить значение даты в JavaScript с помощью свойств value и valueAsNumber элемента input. Например:
var dateControl = document.querySelector('input[type="date"]'); dateControl.value = "2017-06-01"; console.log(dateControl.value); // prints "2017-06-01" console.log(dateControl.valueAsNumber); // prints 1496275200000, a JavaScript timestamp (ms)
Дополнительные атрибуты
В дополнение к общим атрибутам для всех элементов , у «date» есть следующие дополнительные атрибуты:
Атрибут | Описание |
---|---|
max | Максимально возможная дата для установки |
min | Минимально возможная дата для установки |
step | Шаг (в днях), с которым будет изменяться дата при нажатии кнопок вниз или вверх данного элемента |
max
Максимально возможная дата для установки. Если value является более поздней датой, чем дата, указанная в атрибуте max , элемент отобразит ошибку при помощи constraint validation (en-US) . Если в атрибуте max указано значение, не удовлетворяющее формату yyyy-MM-dd , значит элемент не будет иметь максимальной даты.
В атрибуте max должна быть указана строка с датой, которая больше или равна дате, указанной в атрибуте min .
min
Минимально возможная дата для установки. Если value является более ранней датой, чем дата, указанная в атрибуте min , элемент отобразит ошибку при помощи constraint validation (en-US) . Если в атрибуте min указано значение, не удовлетворяющее формату yyyy-MM-dd , значит элемент не будет иметь минимальной даты.
В атрибуте min должна быть указана строка с датой, которая меньше или равна дате, указанной в атрибуте max .
step
Для полей ввода date значение step задаётся в днях; и является количеством миллисекунд, равное 86 400 000 умножить на значение step (получаемое числовое значение хранится в миллисекундах). Стандартное значение step равно 1, что означает 1 день.
Примечание: Для полей ввода date указание для step значения any даёт такой же эффект, что и значение 1 .
Использование полей ввода c типом date
На первый взгляд, элемент выглядит заманчиво — он предоставляет лёгкий графический интерфейс для выбора даты, нормализует формат даты, отправляемой на сервер независимо от локальных настроек пользователя. Тем не менее, есть проблемы с в связи с ограниченной поддержкой браузеров.
В этом разделе мы посмотрим на простые, а затем и более сложные способы использования , и позже дадим советы по уменьшению влияния поддержки браузерами (смотрите Handling browser support).
Примечание: Надеемся, со временем поддержка браузерами станет повсеместной, и эта проблема исчезнет.
Как использовать date?
Самый простой способ использовать — это использовать его с элементами и label, как показано ниже:
form> div> label for="bday">Введите дату вашего рождения:label> input type="date" id="bday" name="bday" /> div> form>
Установка максимальной и минимальной даты
Вы можете использовать атрибуты min и max , чтобы ограничить дату, которую может выбрать пользователь. В следующем примере мы устанавливаем минимальную дату 2017-04-01 и максимальную дату 2017-04-30 . Пользователь сможет выбрать дату только из этого диапазона:
form> div> label for="party">Укажите предпочтительную дату события:label> input type="date" id="party" name="party" min="2017-04-01" max="2017-04-30" /> div> form>
В результате выполнения кода, пользователь сможет выбрать любой день апреля 2017 года, но не сможет выбрать и даже просмотреть дни других месяцев и годов, в том числе через виджет date picker.
Примечание: вы должны уметь использовать атрибут step , чтобы менять количество дней, на которое будет происходить шаг при изменении даты (например, чтобы сделать выбираемыми только субботы). Однако, не похоже, что это где-то применялось на данный момент.
Controlling input size
doesn’t support form sizing attributes such as size . You’ll have to resort to CSS for sizing needs.
Validation
By default, does not apply any validation to entered values. The UI implementations generally don’t let you enter anything that isn’t a date — which is helpful — but you can still leave the field empty or (in browsers where the input falls back to type text ) enter an invalid date (e.g. the 32nd of April).
If you use min and max to restrict the available dates (see Setting maximum and minimum dates), supporting browsers will display an error if you try to submit a date that is outside the set bounds. However, you’ll have to check the results to be sure the value is within these dates, since they’re only enforced if the date picker is fully supported on the user’s device.
In addition, you can use the required attribute to make filling in the date mandatory — again, an error will be displayed if you try to submit an empty date field. This, at least, should work in most browsers.
Let’s look at an example — here we’ve set minimum and maximum dates, and also made the field required:
form> div> label for="party" >Choose your preferred party date (required, April 1st to 20th):label > input type="date" id="party" name="party" min="2017-04-01" max="2017-04-20" required /> span class="validity">span> div> div> input type="submit" /> div> form>
If you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now:
Here’s a screenshot for those of you who aren’t using a supporting browser:
Here’s the CSS used in the above example. Here we make use of the :valid and :invalid CSS properties to style the input based on whether or not the current value is valid. We had to put the icons on a next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can’t be styled or shown effectively.
div margin-bottom: 10px; display: flex; align-items: center; > label display: inline-block; width: 300px; > input:invalid + span:after content: "✖"; padding-left: 5px; > input:valid + span:after content: "✓"; padding-left: 5px; >
Предупреждение: Important: HTML form validation is not a substitute for scripts that ensure that the entered data is in the proper format. It’s far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It’s also possible for someone to simply bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, is of the wrong type, and so forth).
Handling browser support
As mentioned above, the major problem with using date inputs at the time of writing is browser support. As an example, the date picker on Firefox for Android looks like this:
Non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling.
The second problem is the more serious of the two; as we mentioned earlier, with a date input, the actual value is always normalized to the format yyyy-mm-dd . With a text input on the other hand, by default the browser has no recognition of what format the date should be in, and there are lots of different ways in which people write dates, for example:
- ddmmyyyy
- dd/mm/yyyy
- mm/dd/yyyy
- dd-mm-yyyy
- mm-dd-yyyy
- Month dd yyyy
One way around this is to put a pattern attribute on your date input. Even though the date input doesn’t use it, the text input fallback will. For example, try viewing the following example in a non-supporting browser:
form> div> label for="bday">Enter your birthday:label> input type="date" id="bday" name="bday" required pattern="[0-9]-[0-9]-[0-9]" /> span class="validity">span> div> div> input type="submit" /> div> form>
If you try submitting it, you’ll see that the browser now displays an error message (and highlights the input as invalid) if your entry doesn’t match the pattern nnnn-nn-nn , where n is a number from 0 to 9. Of course, this doesn’t stop people from entering invalid dates, or incorrectly formatted dates, such as yyyy-dd-mm (whereas we want yyyy-mm-dd ). So we still have a problem.
div margin-bottom: 10px; > input:invalid + span position: relative; > input:invalid + span:after content: "✖"; position: absolute; right: -18px; > input:valid + span position: relative; > input:valid + span:after content: "✓"; position: absolute; right: -18px; >
The best way to deal with dates in forms in a cross-browser way at the moment is to get the user to enter the day, month, and year in separate controls ( elements being popular; see below for an implementation), or to use a JavaScript library such as jQuery date picker.
Examples
In this example we create two sets of UI elements for choosing dates: a native picker and a set of three elements for choosing dates in older browsers that don’t support the native input.
HTML
The HTML looks like so:
form> div class="nativeDatePicker"> label for="bday">Enter your birthday:label> input type="date" id="bday" name="bday" /> span class="validity">span> div> p class="fallbackLabel">Enter your birthday:p> div class="fallbackDatePicker"> span> label for="day">Day:label> select id="day" name="day">select> span> span> label for="month">Month:label> select id="month" name="month"> option selected>Januaryoption> option>Februaryoption> option>Marchoption> option>Apriloption> option>Mayoption> option>Juneoption> option>Julyoption> option>Augustoption> option>Septemberoption> option>Octoberoption> option>Novemberoption> option>Decemberoption> select> span> span> label for="year">Year:label> select id="year" name="year">select> span> div> form>
The months are hardcoded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year (see the code comments below for detailed explanations of how these functions work.)
input:invalid + span:after content: "✖"; padding-left: 5px; > input:valid + span:after content: "✓"; padding-left: 5px; >
JavaScript
// define variables var nativePicker = document.querySelector(".nativeDatePicker"); var fallbackPicker = document.querySelector(".fallbackDatePicker"); var fallbackLabel = document.querySelector(".fallbackLabel"); var yearSelect = document.querySelector("#year"); var monthSelect = document.querySelector("#month"); var daySelect = document.querySelector("#day"); // hide fallback initially fallbackPicker.style.display = "none"; fallbackLabel.style.display = "none"; // test whether a new date input falls back to a text input or not var test = document.createElement("input"); test.type = "date"; // if it does, run the code inside the if() <> block if (test.type === "text") // hide the native picker and show the fallback nativePicker.style.display = "none"; fallbackPicker.style.display = "block"; fallbackLabel.style.display = "block"; // populate the days and years dynamically // (the months are always the same, therefore hardcoded) populateDays(monthSelect.value); populateYears(); > function populateDays(month) // delete the current set of elements out of the // day , ready for the next set to be injected while (daySelect.firstChild) daySelect.removeChild(daySelect.firstChild); > // Create variable to hold new number of days to inject var dayNum; // 31 or 30 days? if ( month === "January" || month === "March" || month === "May" || month === "July" || month === "August" || month === "October" || month === "December" ) dayNum = 31; > else if ( month === "April" || month === "June" || month === "September" || month === "November" ) dayNum = 30; > else // If month is February, calculate whether it is a leap year or not var year = yearSelect.value; var leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; dayNum = leap ? 29 : 28; > // inject the right number of new elements into the day for (i = 1; i dayNum; i++) var option = document.createElement("option"); option.textContent = i; daySelect.appendChild(option); > // if previous day has already been set, set daySelect's value // to that day, to avoid the day jumping back to 1 when you // change the year if (previousDay) daySelect.value = previousDay; // If the previous day was set to a high number, say 31, and then // you chose a month with less total days in it (e.g. February), // this part of the code ensures that the highest day available // is selected, rather than showing a blank daySelect if (daySelect.value === "") daySelect.value = previousDay - 1; > if (daySelect.value === "") daySelect.value = previousDay - 2; > if (daySelect.value === "") daySelect.value = previousDay - 3; > > > function populateYears() // get this year as a number var date = new Date(); var year = date.getFullYear(); // Make this year, and the 100 years before it available in the year for (var i = 0; i 100; i++) var option = document.createElement("option"); option.textContent = year - i; yearSelect.appendChild(option); > > // when the month or year values are changed, rerun populateDays() // in case the change affected the number of available days yearSelect.onchange = function () populateDays(monthSelect.value); >; monthSelect.onchange = function () populateDays(monthSelect.value); >; //preserve day selection var previousDay; // update what day has been set to previously // see end of populateDays() for usage daySelect.onchange = function () previousDay = daySelect.value; >;
Примечание: Remember that some years have 53 weeks in them (see Weeks per year)! You’ll need to take this into consideration when developing production apps.
Specifications
Specification |
---|
HTML Standard # date-state-(type=date) |
Browser compatibility
BCD tables only load in the browser
Как изменить или убрать иконку у input type date
В хроме, и в некоторых других браузерах для поля input type date добавляется стандартная иконка черного цвета в виде календарика.
Что бы убрать её или изменить пользуем такой псевдоселектор:
/*Так можно перекрасить*/ ::-webkit-calendar-picker-indicator < filter: invert(1); >/*А так убрать*/ input[type=date]::-webkit-calendar-picker-indicator