2016-07-15 104 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

相關問題