首页 > 解决方案 > 如果字段有值,则更改边框颜色

问题描述

我想根据是否有值来更改输入的边框颜色。我不明白为什么条件不起作用。不是检查该字段是否为空,else如果在输入中输入了某些内容,是否应该进入该部分?

class Validation
{
	constructor(field, noticeMessage) {
		this.field    	 	 = field;
		this.noticeMessage   = noticeMessage;
	}

	valid() {
		console.log('coucou');
		this.field.style.borderColor     = "green";
		this.noticeMessage.style.display = "none"; 
		return true;
	}

	invalid() {
		this.field.style.borderColor 	 = "red";
		this.field.focus();
		this.noticeMessage.style.display = "block";
		return false; 
	}

	empty() {
		if (this.field.value == "") {
			this.invalid();
		}
		else {
			this.valid();
		}
	}
}

const titleValidation = new Validation(document.getElementById('name'), document.getElementById('name-notice'));
titleValidation.empty();
<div class="notice">
	<ul>
		<li id="name-notice">The name input must be filled</li>
	</ul>
</div>

<form>
	<label>name</label>
	<input id="name" type="text" name="name">
</form>

标签: javascript

解决方案


不是检查该字段是否为空,如果在输入中输入了某些内容,是否应该进入其他部分?

是的,但想想它什么时候这样做。

它在empty()调用时执行此操作,并且您仅在文档加载时执行此操作。

如果要再次运行测试,则需要再次调用该函数。例如,您可能想在输入元素上注册一个input事件监听器。


推荐阅读