我有一个HTML试图使用jQuery验证的<form>
。到目前为止,我已经知道如果必填字段留空,某些文本会附加到该字段的关联标签上,以通知用户。这是像这样做:jQuery - 根据字段输入切换显示在标签上的文本
$(requiredInputs).on('blur', function(){
//isolate name attribute of field left
var fieldname = $(this).attr('name');
//use name value to find associated label to field
var label = $("#registration label[for='"+fieldname+"']");
//sanitize and store current input value in variable
var inputValue = $.trim($(this).val());
if (inputValue.length === 0){
//new div to be appended to the label
var alert = '<p><small>This is a required field!</small></p>';
//change HTML to inform user
$(label).html(label.html() + alert);
//emphasise input box
$(this).css('border', '2px solid red');
}
});
我也尽快有一个事件,消除了红色的边框一些文本输入:
//turn field back to normal on text entry
$(requiredInputs).on('input', function(){
//de-emphasise input box
$(this).css('border', 'none');
});
我想加入到这个活动是为了摆脱'required field'消息的同时,将标签返回到其原始文本。我不知道该怎么做,因为在添加警告时label.html()
的值已从其原始状态更改。这可以使用某种类型的切换功能来完成吗?
由于提前, 马克
这太好了。非常优雅和清晰,感谢您花时间做到这一点。 – marcuthh