gpt4 book ai didi

javascript - 如何使用 jquery 更改默认必需的选择选项字段消息

转载 作者:行者123 更新时间:2023-12-03 06:32:19 24 4
gpt4 key购买 nike

如何更改必填选择选项字段的默认消息。它是 WooCommerce 产品的变体。我动态添加了该属性,并尝试更改消息,我的下面的代码能够更改消息,但它不起作用。无论是否有选定的值,它总是出现。

JsFiddle

HTML

<select id="color" class="" name="attribute_color" data-attribute_name="attribute_color">
<option value="" selected="selected">Choose an option</option>
<option value="White" class="attached enabled">White</option>
<option value="Black" class="attached enabled">Black</option>
</select>

脚本

jQuery(document).ready(function($) {

$('select#color').prop('required', true);
if( !$('select#color').has('value').length > 0 ) {
$('select#color').attr("oninvalid", "this.setCustomValidity('Please select a color')");
}else{
$('select#color').removeAttr("oninvalid", "this.setCustomValidity('Please select a color')");
}
});

JsFiddle

Required error message

最佳答案

来自 msdn 文档:

Constraint API's element.setCustomValidity() The element.setCustomValidity(error) method is used to set a custom error message to be displayed when a form is submitted. The method works by taking a string parameter error. If error is a non-empty string, the method assumes validation was unsuccessful and displays error as an error message. If error is an empty string, the element is considered validated and resets the error message.

这意味着一旦您setCustomValidity出错,输入将被视为无效,直到您不会通过传递空字符串来重置它。

我下面所做的是检查 select 事件何时发生,并检查 select 是否有值,如果没有,则设置错误,如果有则重置错误。

FIDDLE

jQuery(document).ready(function($) {
var selectColor = $('select#color');
selectColor.prop('required', true);
/* Check if there is no selected value on ready if not mark select as invalid */
if(!selectColor.val()){
selectColor[0].setCustomValidity('Please select a color');
}
/* Do the same check when select value changed */
selectColor.on('change', function(){
if(!selectColor.val()){
selectColor[0].setCustomValidity('Please select a color');
}else{
selectColor[0].setCustomValidity('');
}
})
});

关于javascript - 如何使用 jquery 更改默认必需的选择选项字段消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38394391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com