2016-07-15 101 views
0

如何更改所需的选择选项字段的默认消息。它是WooCommerce产品的变体。我动态地添加了属性,并尝试更改消息,我的波纹管代码能够更改消息,但不起作用。它总是出现,不管是否有选定的值。如何更改使用jquery默认所需的选择选项字段消息

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

+0

当你想这个功能?同时添加数据或'负载'事件? –

+0

首先在'load'之后,'required'和'message'应该可以工作,当选择字段发生变化或者它有一个值时,消息应该消失 – Firefog

回答

1

从MSDN文档:

约束API的element.setCustomValidity() 的element.setCustomValidity(误差)方法被用于设置一个自定义的错误消息,当一个表单提交给被显示。该方法通过获取字符串参数错误来工作。如果错误是非空字符串,则该方法假定验证失败并将错误显示为错误消息。如果错误是空字符串,则该元素将被视为已验证并重置错误消息。

这意味着一旦你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(''); 
    }  
    }) 
}); 
+0

感谢您的回答,您可以给我一个WordPress版本的代码吗? – Firefog

+0

@Firefog如果元素选择器是相同的,它应该工作,无论它是否或它不是wordpress。 –

+0

但wordpress声明'jquery'而不是'$'请检查https://digwp.com/2011/09/using-instead-of-jquery-in-wordpress/ – Firefog

相关问题