Custom Error Validation Message Not Showing - javascript

I am doing error validation in Angular as follows.
<select ng-model = "color" class = "form-control"
ng-options = "color as color for color in colors" required>
<option value="">Choose an option</option>
</select>
<span ng-show="serviceForm.color.$error.required"> My custom error message </span>
The error validation shows up as expected, however, the custom message does not. Instead, I get the following.
This looks nice but how do I replace it with my custom message? It'd be cool if I know where that is coming from so I can edit it.
In addition, my custom message appears if I take out
<option value="">Choose an option</option>
and then it always appears. Why is this?

This message most probably comes from your browser as it does form validaten.
You have to add the novalidate attribute to your form to disable it:
<form novalidate>

Working Plnkr
You can replace HTML5 validation message of that specific field with space on form submit. It will prevent displaying the message and will not affect other HTML5 validation message.
JavaScript:
$scope.ValidateInput = function(){
var email = document.getElementById("colorId");
  if (email.validity.valueMissing) {
    email.setCustomValidity(" ");
  } else {
    email.setCustomValidity("");
}
}
HTML:
<form name='serviceForm'>
<select name='color' id='colorId' ng-model = "color" class = "form-control"
ng-options = "color as color for color in colors" required>
<option value="">Choose an option</option>
</select>
<span ng-show="serviceForm.color.$error.required"> My custom error message </span>
<input type='submit' ng-click='ValidateInput()' value='Submit'>
</form>

<select ng-model = "color" class = "form-control" name="lstColor"
ng-options = "color as color for color in colors" data-msg-required="Please select color from list" required>
<option value="">Choose an option</option>
</select>
Try above and hope will solve your problem

<form novalidate> can be used to avoid these messages.
But you can also use setCustomValidity function when oninvalid event occurs to replace it with your custom message.
Like:
<input class="form-control" type="email" required="" placeholder="username" oninvalid="this.setCustomValidity('Please Enter valid email')"></input>
Helpful explanation here.

Related

Is there a way to disable a dropdown to users while still being able to submit a form with the disabled dropdown?

I have a dropdown that is disabled to the user. I want for the user to be able to press a button that changes the selected item to a different one. For example: from the 4th item in the dropdown to the 7th.
I've tried disabling the dropdown, but when I do that and submit the form, I get a PHP error saying Undefined index: id.
HTML:
<form>
<select id='id' name='id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10'>orange</option>
</select>
<button type='submit'>Submit</button>
</form>
JavaScript:
const dropdown = document.getElementById('dropdown');
const options = dropdown.options;
for (let i = 0; i < options.length; ++i) {
if (options[i].value === id) {
dropdown.selectedIndex = i;
break;
}
}
PHP (This line seems to be the one breaking):
$id = $_POST['id'];
It seems you haven't defined method and action in your form tag. By default, I think, the method is set to 'GET', so when checking 'POST' you'll run into your error.
Therefore, set "method='post'" (and best also an action, e.g. "action='/yourPageName.php') and see if that helps.
I figured out a solution that suits my needs. It was kind of simple. I just enabled the dropdown when I submitted the form, and instantly disabled it again.
id.removeAttribute('disabled');
const data = new FormData(document.getElementById('form'));
id.setAttribute('disabled', '');
request.send(data);
Thanks for the help though :)
A disabled input field will be ignored when you submit the form. I would suggest creating a hidden input field of name="id" if you want the user to view the dropdown but not select it.
<form>
<select id='id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10'>orange</option>
</select>
<input type="hidden" name='id' value="6" />
<button type='submit'>Submit</button>
</form>
You can make an hidden input with the id="id" and change the select id to "temp_id". Then, since you are making the request from javascript, you can just update the hidden field before making the request.
<select id='temp_id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10>orange</option>
</select>
<input type="hidden" name="id" id="id" value="">
Then, on your javascript, just before you make the request, run the code:
document.getElementById("id").value = document.getElementById("temp_id").value;

Select first value by default for a 'Select' box made dynamically

I want to select the first option in a select box by default. The challenge here is that the page might have multiple select boxes as they are created dynamically.
You will understand what I am trying to achieve by looking at my code.
HTML :
<form class="form-inline">
<div class="form-group form-group-grid" ng-repeat="fields in selectedTabData.requiredField" ng-switch="fields.paramType">
<label>{{fields.paramName}}<span class="asterisk" ng-if="fields.mandatory==true">*</span></label>
<input type="text" class="form-control" ng-switch-when="Text" ng-model="fields.fieldValue" ng-attr-id="{{fields.paramName}}Id">
<select class="form-control" ng-switch-when="DropDown" ng-options="field.paramKey as field.paramValue for field in fields.paramData" ng-model="fields.fieldValue" ng-attr-id="{{fields.paramName}}Id">
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary form-inline-grid-button" ng-click="getReport()">Run Report</button>
</div>
</form>
The selected data is available under the model $scope.selectedTabData.requiredField
In Controller I push the selected values in to a variable like :
$scope.selectedTabData.requiredField.forEach(function(item)
{
paramValue.push(item.fieldValue);
paramName.push(item.paramName);
})
I tried doing this :ng-init="fields.fieldValue = fields.paramData[0]"
<select class="form-control" ng-switch-when="DropDown" ng-options="field.paramKey as field.paramValue for field in fields.paramData" ng-model="fields.fieldValue" ng-init="fields.fieldValue = fields.paramData[0]" ng-attr-id="{{fields.paramName}}Id">
</select>
I am not sure how it will work. Can anyone help me out with this?
you can make it possible by ng-repeat inside tag
<select ng-model="fields.fieldValue">
<option ng-repeat="field in fields.paramData" value="{{field.paramKey}}">
{{field.value}}
<option>
</select>
and in controller add this line
$scope.fields.fieldValue = x;
and in this example, x is "field.value" that you want as default selected option.
This is the plunkr for your problem
https://plnkr.co/edit/mahONdv5xQBa5eUZJSoX

How to save selected option(dropdown box) in AngularJS

I want to save selected color value from dd box into $scope.color.
Index.html:
<label class="item item-select" name="selectName">
<span class="input-label">What is your favourite colour?</span>
<select id="colorid">
<option ng-repeat="x in colorList"{{x}}</option>
</select>
</label>
controller.js:
var colorCtrl = function($scope){
$scope.color = "";
$scope.colorList =["red","blue","yellow"];
console.info("color is "+$scope.color);
}
For binding value, use ng-model:
<select id="colorid" ng-model="color">...
for trigger event, use ng-change (calls $scope.onChange() ):
<select id="colorid" ng-model="color" ng-change="onChange()">...
And be careful to your options format! (it is the value which is binded, not the content!)
Full code:
<label class="item item-select" name="selectName">
<span class="input-label">What is your favourite colour?</span>
<select id="colorid" ng-model="color" ng-change="onChange()">
<option ng-repeat="x in colorList" value="{{x}}">{{x}}</option>
</select>
</label>
And JS:
var colorCtrl = function($scope)
{
$scope.color = "";
$scope.colorList =["red","blue","yellow"
];
$scope.onChange = function()
{
//trigerred on color change
console.info("color is "+$scope.color);
}
}
You aleady got many answers here.Just for add on i will suggest you to do this way:
<select style="background:{{color}}" ng-model='color' ng-options='color as color for color in colorList' ng-change='selectionChanged(color)'>
</select>
or you can also try with
<select ng-model='color' ng-change='selectionChanged(color)'>
<options style="background:{{color}}" ng-repeat="color as color for color in colorList" value={{color}}>
{{color}}</options>
</select>
First, there is a syntax error in your code.
In you want to take input from the DOM you have to tell angular which variable to store the input in.
This is done via the ng-model directive.
As given in the documentation.
The ngModel directive binds an input,select, textarea (or custom form
control) to a property on the scope using NgModelController, which is
created and exposed by this directive.
ngModel is responsible for:
Binding the view into the model, which other directives such as input,
textarea or select require.
Providing validation behavior (i.e.
required, number, email, url).
So, if I want to take input I will initialise the input element as,
<input type="text" ng-model="val" />
Via this, I have initialised a variable "val" on the scope (The Model) and I have told angular, whatever input is entered into the input element will be bound to that variable.
<label class="item item-select" name="selectName">
<span class="input-label">What is your favourite colour?</span>
<select id="colorid" ng-model="color">
<option ng-repeat="x in colorList">{{x}}</option>
</select>
</label>
Please check this example.

Angular.js / Ng.select with ng.value

I have the following select:
<select selected="windows" ng-model="wdtype[4][$index]" id="inputEmail1" class="form-control">
<option>app1</option>
<option>app2</option>
<option>app3</option>
</select>
I want that every time that the user select option, the field inputName3 will be reflected. The field defines like this:
<input type="text" class="form-control" ng-model="wdname[4][$index]" id="inputName3" placeholder="Machine Name" disabled>
For example, the user select app1, so the name will be m-app1. If the user select app2, the name will be displayed: m-app2.
I don't see any trigger in angular which can help me in this case.
You can define values for options like this
<option value="m-app1">app1</option>
<option value="m-app2">app2</option>
<option value="m-app3">app3</option>
Or make it in a generic way. Define a function in scope that transforms selected value the way you need.
In controller:
$scope.getMachineName = function () {
if (wdtype[4][$index]) return '';
return 'm-' + $scope.wdtype[4][$index];
}
In template
<input type="text" class="form-control" value="{{getMachineName()}}"

Jquery validation plugin and switching required field

Yup, basically, I am building a web form that need to provide different required form and validation function fallow by selected country.
I am using
<script type="text/javascript" src=" jquery-1.3.2.min.js" charset="utf-8"></script>
<script type="text/javascript" src=" jquery.validate.js" charset="utf-8"></script>
and here is my JS code
<script type="text/javascript" charset="utf-8">
function updatRequreForm (STATE,ZIPCODE) {
$("#frm_verification").validate({
rules: {
'form[country]' : "required",
'form[state]' : {required: STATE},
'form[zip]': {required: ZIPCODE},
},
messages: {
'form[country]' : "This field is required.",
'form[state]' : "This field is required.",
'form[zip]': "This field is required.",
});
};
function setRequreForm () {
var _cs = $('#country_select')[0];
if ('US' != _cs.value)
{
$('#state_star')[0].innerHTML = '';
$('#zip_star')[0].innerHTML = '';
updatRequreForm (false,false);
}
else
{
$('#state_star')[0].innerHTML = '*';
$('#zip_star')[0].innerHTML = '*';
updatRequreForm (true,true);
}
};
$(document).ready(function() {
setRequreForm ();
$('#country_select').change(function(){
setRequreForm ();
});
});
</script>
Here is my HTML:
<form id="frm_verification" action="some.php" method="POST">
<label for="country_select"><sup>*</sup>Country:</label>
<select name="form[country]" id="country_select">
<option value="">- Select -</option>
<option value="US" selected="selected">United States</option>
<option value="ZM">Zambia</option>
<option value="ZW">Zimbabwe</option>
</select>
<label for="select-state"><sup id="state_star">*</sup>State/Province/Region:</label>
<span id="states_select">
<select id="select-state" name="form[state]">
<option value="">- Select -</option>
<option value="AK">Alaska</option>
</select>
</span>
<span id="states_text" style="display:none;">
<input type="text" name="form[state]" value="" id="state" />
</span>
<label for="zip_code"><sup id="zip_star">*</sup>ZIP/Postal Code:</label>
<input type="text" id="zip_code" name="form[zip]" value="" id="zip">
<input type="submit" value="Submit" id="submit_btn" class="submit">
</form>
Basically, what I need to create is:
1.When user select US on country selection, the State and Zip area become required.
2.When user select Zambia on country selection, the State and Zip area become non-required.
Problem:
When I first load the page and click the Submit button with empty field, the form successfully validate each fields and shows warning. However selecting of the Zambia, the validation is not working.
Guess:
I have removed “setRequreForm ();” on ready function like:
$(document).ready(function() {
//setRequreForm ();
$('#country_select').change(function(){
setRequreForm ();
});
});
And tried to select Zambia, and tried to validate the form and it works. So I think calling “validate()” twice causes error.
Well I stuck with this for a while. Please help me to figure this out, I will really appreciate that.
You can't call validate more than ones becouse you run validate plugin more than one and this lead to errors.
You can setup your validator like this:
$("#myform").validate({
ignore: ".ignore"
})
Ignore tells to validator: field which has ignore css class should not be validated.
When you change requirements then add to specified fields css class "ignore":
$("#field1").addClass("ignore");
otherwise remove this class:
$("#field2").removeClass("ignore");

Categories

Resources