Smaller Work around for ng-pattern on Select - javascript

I am working on an angular app and I needed to put a pattern validation on a select element. Just using ng-pattern on select didn't work. So I created a hidden input with same model with ng-pattern on the hidden input, that didn't work either. So I created a text input with the ng-pattern and hid it via css. Which works beautifully.
Is there a smaller work around for this?
EDIT1: I think I should have added that the options are generated by ng-options
EDIT2: Edited the code snippet accordingly to show what I actually want.
function formCtrl($scope) {
$scope.options = ['Please Select','Value 1','Value 2'];
$scope.price = 'Please Select';
$scope.onSubmit = function (form) {
console.log(form.$valid);
}
}
.show-none {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit(myForm)">
<select ng-model="price" ng-options="o as o for o in options"></select>
<input type="text" class="show-none" ng-pattern="/^(?!.*(Please Select))/" ng-model="price" name="price_field"> <span ng-show="myForm.price_field.$error.pattern">Not a valid option!</span>
<input type="submit" value="submit" />
</form>
</div>

You shouldn't use ng-pattern with hidden input field for this case, you should add value for each option, & then you should have required attribute make sure any of the option should selected before submiting. Adding name="price" will add form element to myForm object.
Markup
<select ng-model="price" name="price" required>
<option>Please Select</option>
<option value="TEST1">TEST1</option>
<option value="TEST2">TEST2</option>
</select>
Update
If you wanted to make it using ng-options then it would be something like below. You don't need to add Please Select in your array, you could add it manually inside select
Markup
<form name="myForm" ng-submit="onSubmit(myForm)" novalidate>
<select ng-model="price" ng-options="o for o in options" required>
<option value="">Please select a person</option>
</select>
<input type="submit" value="submit" />
</form>
Code
(function(angular) {
'use strict';
angular.module('staticSelect', [])
.controller('formCtrl', ['$scope', function formCtrl($scope) {
$scope.options = ['Value 1', 'Value 2'];
$scope.onSubmit = function(form) {
console.log(form.$valid);
}
}]);
})(window.angular);
Demo here

You can also just disable certain options if you didn't want it to be possible to select them in the first place:
<select ng-model="price">
<option disabled>Please Select</option>
<option>TEST1</option>
<option>TEST2</option>
</select>

Chiming in here as this is something that comes up time and time again and the suggested solutions here don't work for me. This is a really common use-case too.
I tried putting an empty option in, and it didn't work for me. I noticed that AngularJS was placing a value attribute in with the same value as the contents of the <option> tag. The select was ng-valid even with this option selected.
In my scenario I have placed the placeholder option i.e. SELECT A CENTRE as the first item in the list of locations (the scope variable I bind the options to). I hide the first item with conditional CSS, but select it initially by setting dc.user.CentreName to SELECT A CENTRE in the controller. This gives us the behaviour of it disappearing when the user has clicked any other option. Another option is to disable it which means it will still show at the top of the list but will be unselectable after selecting another item (was added in Angular 1.4x). I have also put that code in (the ng-disabled attribute), to illustrate this. You may safely remove it if you want to go the hidden route.
Next we want to use the standard Angular forms validation to ensure that some item other than the first is selected. I tried the other suggested approaches of putting in an empty option (with no value) and setting required on the select. So I went for a hidden input form element with a required and ng-pattern attribute using a negative lookahead assertion.
Note that we use ng-class to bind ng-valid and ng-invalid to the select so existing CSS styling will work.
Feels a bit hacky but it works.
<select ng-model="dc.user.CentreName"
ng-class="{'ng-valid': orderForm.centreName.$valid, 'ng-invalid': !orderForm.centreName.$valid }">
<option ng-repeat="location in locations"
ng-disabled="$index < 1"
ng-style="$index < 1 && {'display': 'none'} "
value="{{location}}">
{{location}}
</option>
</select>
<input
type="hidden"
ng-model="dc.user.CentreName"
ng-pattern="/^(?!SELECT)/"
required/>
And in the controller... (note you can also use ng-init to set the placeholder value declaratively from the view, see https://stackoverflow.com/a/13775151/4707368)
function ShoppingController($scope [...]) {
[...]
$scope.dc = {
user: {
"CentreName": 'SELECT A CENTRE',
[...]
Your CSS might look like this:
input.ng-touched.ng-invalid, select.ng-invalid
{
background-color: rgba(199, 35, 35, 0.15);
}
input.ng-touched.ng-valid, select.ng-valid
{
background-color: rgba(116, 173, 39, 0.16);
}

Related

How to make a <div> show only when a certain <select> dropdown option is selected? The <select> options are populated with the ng-repeat directive

I have a select dropdown list populated with the angularjs ng-repeat directive. I would like for a div to show only when a certain option is selected.
Here is the code:
<select type="text"
class="form-control"
ng-model="vm.request.requestType"
name="requestType" id="requestType"
placeholder=""
required>
<option selected></option>
<option value="test">test</option>
<option ng-repeat="requestType in vm.requestTypes">{{requestType}}</option>
</select>
<script>
$(function() {
$("#requestType").change(function () {
if ($("#test").is(":selected")) {
$("#continueCheckbox").show();
} else {
$("#continueCheckbox").hide();
}
}).trigger('change');
});
</script>
<div id="continueCheckbox">
<input type="checkbox"
name="continueCheckbox"
value="continueCheckbox">
Check this box to continue, and to confirm that you have read the
Documentation
</div>
The "test" option is just for testing if the function works. Currently, the checkbox displays no matter what is selected, and never disappears.
I highly recommend not mixing AngularJS and jQuery. Both are DOM manipulation frameworks and do not work well together. Here is one way you could accomplish what you are after with AngularJS:
<div id="continueCheckbox" ng-if="vm.request.requestType === 'test'">
<input type="checkbox"
name="continueCheckbox"
value="continueCheckbox">
Check this box to continue, and to confirm that you have read the Documentation
</div>
Have you tried using the ng-class directive?
<div id="continueCheckbox" ng-class="selected: vim.request.requestType === 'test'"></div>
Then handle the style in .css file
.selected {
display: none;
}
If you wanted to use jQuery, you could just check the value of the select. You have it set up already.
var selectType=$(this).val();
if (selectType=="test") // instead of if ($("#test").is(":selected"))
You could also use vanilla JS with .value to do your comparison.

Make bootstrap-select dropdown required

I have dropdown list in my form which used bootstrap-select to show the dropdown. I want to make if user submit the form it will check the dropdown is have value or not. I already added required inside the <select> tag but nothing happen if I leave it empty and press submit button.
This is my code :
<div class="form-group">
<label for="location">Location</label>
<select name="location" id="location-form" required>
<option value="">Choose Location</option>
<?php foreach($location as $row) : ?>
<option value="<?=$row['location_id']?>"><?=$row['location_name']?></option>
<?php endforeach; ?>
</select>
</div>
How to make my select dropdown required and can validate it must filled in if user press submit button ? Thanks before.
A select always has a value set into it. Try using a radio group instead.
Check here for more information on a radio group. HTML5: How to use the "required" attribute with a "radio" input field
There is two way that helps me will share with you below.
Using this way also problem getting solved.
<form action="whatever" method="post" novalidate>
OR using this too
please try following code.
/* For checking the drop-down contain value of not use this. */
if(jQuery('#location-form').val() == ''){
alert('Please select the option for location');
}else{
return false;
}
I hope this will help you.
Thanks.
By using default bootstrap 4.* JS validations you can simply add to sezel
<select ... required="true">
and an empty option with value=""
<option value="">Select one</option>
In this way Bootstrap JS library check if is selected
Add "disabled" in yout first option(along with required in select tag) as:
<div class="form-group"> <label for="location">Location</label> <select name="location" id="location-form" required> <option value="" disabled>Choose Location</option> <?php foreach($location as $row) : ?> <option value="<?=$row['location_id']?>"><?=$row['location_name']?></option> <?php endforeach; ?> </select> </div>
I am new to coding but I have done a lot of research on this site and I found a solution (not so efficient but works). This solution is based on the fact that the html5 "required" attribute worked at least somewhat - it prevents you from proceeding next or submitting but nothing else other than that - e.g. no error message, no alert, nothing at all.
The idea of the solution is to use the "invalid-feedback" class to show an error message, make use of the fact that it won't show until you pass in a "d-block" class. Then use a couple of functions on click of a button.
$('#button').click(function () {
$('#id-error').hide(); //if there is indeed a html5 message showing, but it looks bad, then just hide it, if you inspect the msg, html has automatically generate this "id-error" id
if ($('#id').is(':disabled')){
$('#errormsg-id').removeClass('d-block');
} else if (!$('#id').val()){
$('#errormsg-id').addClass('d-block');
};
});
$('#id').change(function () {
if($('#id').val()){
$('#errormsg-id').removeClass('d-block');
};
});
<div class="form-group ">
<select id="id" class="selectpicker" required>
<option >...</option>
</select>
<div id="errormsg-id" class="invalid-feedback ">Please make a selection.</div>
</div>
This is PHP; however, for Angular (which is what I came here looking for), you could create a custom validator that checks if the <option value="">Choose Location</option> is selected. Inside the validator, you'd check the value of the control. If the control value is '', then you fail the validation.
This would work for both template driven and reactive forms.
Custom Validators in Angular
Have you put your select in form tag?
If not try placing it inside form tag.
Please refer - https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_select_required
If required is not working you can add java script validation as given below and replace "FormnameId" with your form tag id.
<script type="text/javascript">
$(document).on('submit','form#FormnameId',function(event){
event.preventDefault();
var sel = $("#location-form").val();
if(sel == ''){
alert('Please select value first');
return false;
}
});
</script>

Disable selectbox with ng-options in angularjs

Hello how can I disable a select box, so that a user can only see the actual value of the select box and can't change the content inside. It's for an ionic framework mobile application.
My select box is looking like this one here:
<select ng-class="nightMode"
ng-options="option as option.label for option in item.Options track by option.id"
ng-change="item.Call(item.SettingKey,item.Checked.id)"
ng-model="item.Checked">
</select>
I tried with ng-disabled, disable inside the ng-options, ng-readonly but none of these worked for me. So what is the correct way to achieve this?
ng-disable example:
<select ng-class="nightMode"
ng-options="option as option.label for option in item.Options track by option.id"
ng-disabled="true"
ng-change="item.Call(item.SettingKey,item.Checked.id)"
ng-model="item.Checked">
</select>
Update:
I tried one of the workarounds like suggested:
<select ng-class="nightMode"
ng-change="item.Call(item.SettingKey,item.Checked.id)"
ng-model="item.Checked">
<option ng-repeat="option in item.Options" value="option.id" ng-disabled="true" ng-selected="item.Checked.id==option.id">{{option.label}}</option>
</select>
But I can switch to a empty entry inside the select box and set the value of the selectbox to undefined.
Your code snippet not clear yet. But i can disable this select using disabled="true" .
Check out my working
http://plnkr.co/edit/xDefIzZ3YleYcyAmQYHj?p=preview
Here are better code snippet editor :
http://plnkr.co/
http://jsfiddle.net/
I guess your logic is wrong,
If you don't want to change content in selectbox, then it's not going to be a select element, just use an input and assign a model to it, then something changed, change the value of it.
<input type="text" name="selectedId" ng-model="selectedId" />
Other Implementation:
If you want to open select and don't able to select them,
then add your dynamic data to
var datas = [
{
"value" : "foo",
"id" : "0111",
"selectable": false
},
{
"value" : "foo",
"id" : "0111",
"selectable": true
}
];
Then use it on option element;
<option ng-repeat="option in item.Options" value="option.id" ng-disabled="true" ng-disabled="item.selectable">{{option.label}}</option>
Well it turned out that this was a ionic-framework item-select problem.
I found this issue to solve my problem:
https://github.com/driftyco/ionic/issues/1549
Like suggested there I end up adding a class to my select box which looks like this:
.style-disabled {
pointer-events: none;
}
And my select box is now looking like this:
<select class="style-disabled"
ng-class="nightMode"
ng-disabled="someCondition"
ng-options="option as option.label for option in item.Options track by option.id"
ng-change="item.Call(item.SettingKey,item.Checked.id)"
ng-model="item.Checked">
</select>
You can't do it the way you want, but there are some work around in previously asked question, check them 1 , 2
<div ng-app="myapp">
<form ng-controller="ctrl">
<select id="t1" ng-model="curval">
<option ng-repeat="i in options" value="{{i}}" ng-disabled="disabled[i]">{{i}}</option>
</select>
<button ng-click="disabled[curval]=true">disable</button>
</form>
angular.module('myapp',[]).controller("ctrl", function($scope){
$scope.options=['test1','test2','test3','test4','test5'];
$scope.disabled={};
})
I hope that helps, good luck

how to use datalist in angularJs

Below i mention datalist sample code using angularjs,
here my problem is what ever i am typing the text box, in controller add by added every words,in my requirement in datalist selected details only shows in controller,
<input list="browsers" name="browser" ng-model="SelectedDoctor" ng-change="LoadSessionData(SelectedDoctor)">
<datalist id="browsers" >
<option data-ng-repeat="Doctor in DoctorsList" value="{{Doctor.Name}}" id="doctorList"> </option>
</datalist>
In Controller
$scope.LoadSessionData(doctorName){ console.log(doctorName) }
At the outset, This line seems wrong syntactically,
$scope.LoadSessionData(doctorName){ console.log(doctorName) }
should change to,
$scope.LoadSessionData = function (doctorName){ console.log(doctorName) }
Works fine here

Changing the placeholder text based on the users choice

jQuery is permitted, but an HTML-only solution is preferred.
I have a select box with a couple of options. When the user selects 'Name', I want the placeholder text 'Enter your name' to appear in the adjacent text-box.
Likewise for 'ID' -> 'Enter your ID'.
See http://jsfiddle.net/Uy9Y3/
<select>
<option value="-1">Select One</option>
<option value="0">Name</option>
<option value="1">ID</option>
</select>
<input type="text">
This is a requirement by a client that I haven't been able to figure out.
If it helps, the website is using the Spring framework.
Since you need to update the placeholder when the select updates, you'll need to use javascript to do it.
You could set the placeholder you would like to display as an attribute on each option element using the HTML5 data- style attributes. Then use jQuery to attach a change event listener which will update the placeholder attribute of the input box.
Note that the placeholder attribute doesn't have any effect in older versions of IE, so if you need to support old IE you'll need to polyfill that functionality with another library.
Working Demo
HTML
<select id="mySelect">
<option data-placeholder="" value="-1">Select One</option>
<option data-placeholder="Enter your name" value="0">Name</option>
<option data-placeholder="Enter your ID" value="1">ID</option>
</select>
<input id="myInput" type="text">
jQuery
$('#mySelect').on('change', function() {
var placeholder = $(this).find(':selected').data('placeholder');
$('#myInput').attr('placeholder', placeholder);
});
It requires JavaScript. You can do it inline -- if that's what you mean by HTML-only.
<select onchange="document.querySelector('input').setAttribute('placeholder', 'Enter your ' + this.options[this.selectedIndex].text);"></select>
See the following jsfiddle for an example of how to do this:
http://jsfiddle.net/sW6QP/
Note that this is using jQuery ONLY because jsfiddle seems to be unable to find the function placed into the onChange event.
If you want to do it without jQuery, change the select line to this:
<select id="selectionType" onChange="setPlaceholder();">
And instead of $("#selectionType").on("change",function() {, do this instead:
function setPlaceholder() {
(make sure to change the }); to } as well)

Categories

Resources