Firefog Firefog - 4 months ago 23
HTML Question

How to change the default required select option field message using jquery

How can I change the default Message of a required select option field. Its a variation of WooCommerce's product. I added the property dynamically and try to change the message my bellow code able to change the message but it not works . It always appearing no matter if there is a selected value or not.

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>


Script

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

Answer

From the msdn docs:

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.

It means that once you setCustomValidity error the input will be considered as invalid till you wont reset it by passing empty string.

What I did below is checking when select event happened and check if select has value if it doesn't then set error if it has then reset error.

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('');
    }    
  })
});