HTML5/JS/jQuery:对于无效的输入,将不同的(任意的)元素标记为无效
HTML5/JS/jQuery: On invalid input, mark a different (arbitrary) element as invalid
我正在尝试创建一个标准的新密码形式,在那里你输入新密码一次,然后第二次确认。我希望这样,一旦您模糊了这些字段,如果它们不匹配,两个将被标记为无效,如下面的场景:
- 用户在
#newpassword1
中输入密码abc
- 用户标签到
#newpassword2
。 - 用户在
#newpassword2
中输入密码def
- 用户标签离开。
- 验证检测到不匹配,并将
#newpassword1
和#newpassword2
标记为无效。
我知道我可以通过使用e.target.setCustomValidity(...)
将事件的目标标记为无效,但我不太了解JavaScript的事件模型,也不知道如何根据事件目标本身的无效将不同的元素标记为无效。
这是我试图使用的(非工作)代码的相关摘录:
if ( $('#newpassword1').val() != $('#newpassword2').val() ) {
errorMessage = "The new passwords you've entered don't match.";
$('#newpassword1, #newpassword2').setCustomValidity(errorMessage);
}
从直觉上看,这似乎应该工作,但当然不是这样。错误只是TypeError: $(...).setCustomValidity is not a function
。
请注意:我不是在问如何添加一个红色的环或任何到一个字段,我希望它实际上是无效(如在,有它的validity.valid
属性返回false
)。
这是可能的吗?
谢谢!
试试下面的代码。你得到这个错误是因为jQuery返回一个选定对象的数组,因为setCustomValidity
是由本地输入元素而不是jQuery对象支持的,你看到这个错误。
$('#newpassword1, #newpassword2').each(function() {
this.setCustomValidity(errorMessage)
});
<div class="cabinet_settings_header cabinet_header">Список регионов работы для выбора</div>
<div class="registration_region_select checkbox-group required">
<?for($i = 0; $i < sizeof($regions); $i++):?>
<label for="region_id_<?=$regions[$i]['region_id']?>">
<input type="checkbox" name="region_id[]" value="<?=$regions[$i]['region_id']?>" id="region_id_<?=$regions[$i]['region_id']?>" />
<?=$regions[$i]['name']?>
</label>
<?endfor;?>
</div>
<div class="cabinet_settings_header cabinet_header">Проверка выбора регионов работы (разрешмет отправку формы, если минимум 1 выбран)</div>
$('.checkbox-group.required input').on('change', function(){
checkRegions();
});
function checkRegions(){
checked_counter = $('.checkbox-group.required :checkbox:checked').length;
if(checked_counter > 0){
$('.checkbox-group.required #region_id_2')[0].setCustomValidity('');
}else{
$('.checkbox-group.required #region_id_2')[0].setCustomValidity('Выберите хотябы 1 из вариантов');
}
}
$(document).ready(function() {
checkRegions();
$("form").submit(function(event){
if($('.checkbox-group.required :checkbox:checked').length <= 0 ){
$('.checkbox-group.required #region_id_2').focus();
event.preventDefault();
}
})
});
相关文章:
- 如果我在javascript中输入无效的电子邮件或空白,如何显示特定的文本框边框红色
- 使用CSS或js,使用动态选择器选择任意li的下一个元素
- jquery代码在Mozilla中有效,但在其他浏览器上无效
- 这个问号在Flow中意味着什么:“;?()=>“无效”;
- 从字符串末尾删除空白无效
- Jquery Datatables错误:无效的JSON基元:draw
- 滚动在Chrome中有效,但在Firefox或IE中无效
- 错误:语法错误,无法识别的表达式:不支持的伪:无效/RectJS/Unit Testing
- 我们可以使用任意的编程语言来动态化HTML页面吗
- Javascript setattribute-名称和值无效
- 格式化货币无效
- JavaScript错误无效的限定符
- 按键事件无效的原因
- RegExp匹配任意字符串+8位数字
- Laravel数据表无效的JSON响应
- 文本字段显示它是有效的,即使它在ExtJS中是无效的
- JS代码在jsbin中有效,在jsfiddle或Chrome/Safari中无效
- 如何使用JavaScript粘贴原始二进制文件而不出现“无效字符”错误
- HTML5/JS/jQuery:对于无效的输入,将不同的(任意的)元素标记为无效
- {"error ":["无效的图像URL"]}与任意集成