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

时间:2016-07-15 10:55:26

标签: javascript jquery html

如何更改所需选择选项字段的默认消息。它是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

2 个答案:

答案 0 :(得分:1)

来自msdn docs:

  

Constraint API的element.setCustomValidity()   element.setCustomValidity(error)方法用于设置在提交表单时显示的自定义错误消息。该方法通过获取字符串参数错误来工作。如果error是非空字符串,则该方法假定验证不成功并将错误显示为错误消息。如果error为空字符串,则认为该元素已验证并重置错误消息。

这意味着一旦出现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('');
    }    
  })
});

答案 1 :(得分:0)

试试这个

$('select#color').on('invalid', function () {
    return this.setCustomValidity('Please select a color.');
}).on('change', function () {
    return this.setCustomValidity('');
});