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
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('');
}
})
});
Try this one
$('select#color').on('invalid', function () {
return this.setCustomValidity('Please select a color.');
}).on('change', function () {
return this.setCustomValidity('');
});
Related
I have both a dropdown list and a "multiple" dropdown list like below
#Html.DropDownList("process", Model.Processes, new { placeholder = "-- select --", style = "width: 100%", multiple = "multiple" })
#Html.DropDownList("products", Model.Products, new { placeholder = "-- select --", style = "width: 100%" })
And I used the reset code from this link http://www.webcodeexpert.com/2014/12/how-to-reset-aspnet-dropdownlist-or.html
I got it to work as I intended, where the values are cleared/reset, but what I would like to ask is how to reset the text in the dropdown list back to either the --select-- part or leave it blank for the "multiple" dropdown. I have a button i used to call the javascript function and i used this code to make it work.
function clearAll() {
$('#products').find('option:first').prop('selected', true);
$('#products').val('0');
}
i tried the .val('0') part but the text on the dropdown still stays the same as what was selected but the value was assigned back to the default.
You can make use of the defaultSelected property of an option element:
Contains the initial value of the selected HTML attribute, indicating whether the option is selected by default or not.
So, the DOM interface already keeps track which option was selected initially.
$("#reset").on("click", function () {
$('#my_select option').prop('selected', function() {
return this.defaultSelected;
});
});
This would even work for multi-select elements.
If you don't want to iterate over all options, but "break" after you found the originally selected one, you can use .each instead:
$('#my_select option').each(function () {
if (this.defaultSelected) {
this.selected = true;
return false;
}
});
Have you tried the button type="reset"? This would reset all input's of your form. Also the selects. When you want to reset all your fields I would try this solution because it wouldn't need any additional JavaScript code.
<form>
<select name="select1">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select name="select2" placeholder="placeholder">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<button type="reset">Reset</button>
</form>
I have a select area for the user:
<select class="span12" placeholder="Enquiry Type" name="enquiry" id="enquiry">
<option value='' selected></option>
<option value='cv'>Submit CV</option>
<option value='vacancy'>Submit Vacancy</option>
</select>
I have a hidden field in the form which allows the user to upload their cv. I now need it so that if the user selects submit cv, the field will display itself.
<input type="file" name="cv" accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" style="display:none;">
I know that i would be able to check the user input of the select using an on click function. Is there a way of doing it without that (there and then)? And then if that option is selected, display the hidden file upload.
Try this:
$('#enquiry').on('change', function(e) {
if($(this).val() === "cv") {
$('input[name="cv"]').show();
}
});
This works:
http://jsfiddle.net/dL8evt33/
:)
You can achieve this by hooking to the change event of the select and checking the selected value. You can then use toggle() to hide or show the input as needed. Try this:
$('#enquiry').change(function() {
$('input[type="file"]').toggle($(this).val() == 'cv');
});
Example fiddle
remove display: none; first now do write this code.
$("[id$=fileupload]").hide();
if("[id$=enquiry]").val('cv')
{
$("[id$=fileupload]").show();
}
else
{
$("[id$=fileupload]").hide();
}
On change event you can display the input type file using its id. Give 'file' as id to hidden field -
$('#enquiry').on('change', function() {
if("cv" == this.value){
jQuery("#file").show(); // or jQuery("#file").toggle();
}
});
I want to show a warning message if a user selects a specific option, but the warning isn't appearing. How can I modify my code so that this works correctly? Here is a demo on jsFiddle which reproduces the problem?
HTML :
<input type="text" id="mail_address"/>
<select>
<option value='google.com'>google.com</option>
<option onClick="warningaa()" value=''>Don't send mail</option>
</select>
JS:
function warningaa() {
alert('If you choose this option, you can not receive any information');
}
You can not use on click action in dropdown option. One solution is to use change on select element:
html
<input type="text" id="mail_address" />
<select onchange="warningaa(this);">
<option value='google.com'>google.com</option>
<option value='error'>error</option>
</select>
js
function warningaa(obj) {
if(obj.value == "error") {
alert('If you choose this option, you can not receive any infomation');
}
}
fiddle
The option tag does not support the onclick event. Use the onchange event on the select instead.
HTML
<input type="text" id="mail_address"/>
<select id="selectbox" onchange="warning(this)">
<option value='google.com'>google.com</option>
<option value='warning'>Do not send me any kind of shit</option>
</select>
JS
function warning(obj) {
if(obj.value == 'warning') {
alert('If you choose this option, you can not receive any infomation');
}
}
You need to set an event handler on the SELECT element, and watch the "value" of select, as below:
document.getElementById('mySelect').addEventListener('change', warn, true);
function warn(e) {
e.preventDefault();
e.stopPropagation();
if (e.currentTarget.value === 'the value you want') {
// do something
} else {
return;
}
The key here is using CHANGE event vs CLICK, since you want to react to a "change in value" and if that value = something, warn the user.
using addEventListener is also a better approach overall, it clearly distinguishes your HTML from your JavaScript.
More on this here:
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener
and here:
https://developer.mozilla.org/en/docs/Web/API/Event
I have problem with Mootools formcheck js when applying custom function to Selectbox field. Custom Function will be work fine with Text Field, but Selectbox is NOT.
My dummy code of Custom Function:
var customFunc = function customFuncF(el) {
el.errors.push('Custom function!!!');
return false;
};
And There are a simple form that I apply to a text field:
and
<input type="text" class="validate['%customFunc']" id="User_lastName" name="User[lastName]" >
-> It works fine with text field.
But when I apply custom function to Selectbox field, example as Office list in my simple form, it's seems not work and always returns true. My example code for Selectbox
<select id="User_officeId" class="validate['%customFunc']" name="User[officeId]" >
<option selected="selected" value="">-Select Office-</option>
<option value="1">Office A</option>
<option value="2">Office B</option>
</select>
How can I apply custom function to Selectbox field?
Thanks,
It was caused by your validate which excludes the keyword 'required'. In fact, the custom function works.
But in function 'manageError':
manageError : function(el, method) {
...
} else if ((isValid || (!el.validation.contains('required') && !el.value))) {
this.removeError(el);
return true;
}
return true;
},
As no 'required' and no value in here, the pushed error was be removed. :(
You can add the word 'required' into validate[] or setup the value of first option to 0 instead of blank.
I am using jQuery validation plugin for client side validation, but my validation does not work on my select box.
HTML
<select id="select" class="required">
<option value="-1">Choose</option>
<option value="child">test2</option>
</select>
JavaScript
$("#formid").validate({
select: {
required: function(element) {
if ($("#select").val() == '-1') {
return false;
} else {
return true;
}
}
}
});
How do I get this working?
A simple way to fix this problem is to give the non valid option the value of "". Then simply call validate on your form and it will not submit when "Choose" is selected.
HTML
<form id="formid">
<select name="select" class="required">
<option value="">Choose</option>
<option value="child">test2</option>
</select>
<input type="submit" />
</form>
JavaScript
$("#formid").validate();
Demo
Although this probably works with some of the aforementioned methods,if you're looking to use a custom validation function, you should use addMethod as documented here: http://docs.jquery.com/Plugins/Validation/Validator/addMethod
So you would first add the method through something like
$.validator.addMethod("requiredSelect", function(element) {
return ( $("#select").val() !='-1' );
}, "You must select an option.");
Then simply assign the validator with
$("#formid").validate({
rules: {
select: { requiredSelect : true }
}
});
For some reason no solution provided worked in my case, it boiled down to jQuery Validate calling the "optional" check on the value of the drop down, which that called the !required rule.
When the select box selected an empty value, the required showed "false" which inverted meant it was always optional when the required failed, so it never ran the required rule.
I overwrote the optional function with the below, which returned "False" on optional if it was a required item:
// Get Select to work
$.validator.prototype.optional = function (element) {
var val = this.elementValue(element);
// Custom logic to get Select to show validate when value is empty
if (element.nodeName.toLowerCase() === "select") {
if (element.hasAttribute("data-val-required") || element.hasAttribute("required")) {
return false;
}
}
return !$.validator.methods.required.call(this, val, element) && "dependency-mismatch";
};
instead of:
$("#select").val()
try:
$("#select :selected").val()
$("#select").val() returns all the option values instead of the selected one.
Here, my assumption is that you want to check if the user has chosen the option -1 when the control report-crime is validated.
by default
<option value="">Choose</option>
works with
required: true
There is missing name attribute in your select element.
In my case that was the issue since the jQuery Validatation Plugin looks for the name not id while validating.