Я пытаюсь использовать <label>
элементов в моей форме контакта html, такой как атрибут заполнителя HTML5 для ввода. Я написал следующий JavaScript, чтобы действовать как функция многократного использования, которая обеспечит следующие функции.Использование меток, таких как HTML5 placeholder
- Найти данные по названию.
- Получите значение ввода.
- Найдите ярлык, принадлежащий входу.
- Изменение стиля этикетки в зависимости от состояния входа.
- Изменение стиля этикетки в зависимости от значения ввода.
Однако он не работает, и я не знаю, почему, поскольку на консоли не появляются ошибки. Что я делаю не так? here is a JS Fiddle with code
function placeholder(field_name) {
// Get the input box with field_name
// Then get input value
var box = document.getElementsByName(field_name);
var i;
for (i = 0; i < box.length; i++) {
var value = document.getElementById(box[i].value);
}
// Get the labels belonging to each box using the HTML for attribute
var labels = document.getElementsByTagName('LABEL');
for (i = 0; i < labels.length; i++) {
if (labels[i].htmlFor !== '') {
var elem = document.getElementById(labels[i].htmlFor);
if (elem) {
box.label = labels[i];
}
}
}
// Colors
var focusColor = "#D5D5D5";
var blurColor = "#B3B3B3";
// If no text is in the box then show the label grey color
box.onblur = function() {
box.label.style.color = blurColor;
};
// If input focuses change label color to light grey
box.onfocus = function() {
box.label.style.color = focusColor;
};
// If there is text in the box then hide the label
if (box.value !== "") {
// Quick do something, hide!
box.label.style.color = "transparent";
}
}
// Call the function passing field names as parameters
placeholder(document.getElementsByName("email"));
placeholder(document.getElementsByName("firstName"));
placeholder(document.getElementsByName("lastName"));
Теперь, как вы сравниваете '' label' и placeholders'? –
'var box = document.getElementsByName (имя_поля);' - 'box' является _NodeList_. 'if (elem) box.label = labels [i];' Установка нового свойства _label_ на _NodeList_. Кроме того, «var» внутри цикла меня огорчает. –
@PaulS. Что именно он здесь делает? он извлекает значения заполнителя, но для чего? 'placeholder (document.getElementsByName (« email »));' –