Validating select element based on pattern with AngularJS - javascript

I'm developing an Angular app and I have a form set up which I need to run validation on. One of the form elements is a <select>, like this:
<select name="noOfPeople" ng-model="noOfPeople">
<option>No of people*</option>
<option ng-repeat="amt in [] | range:12">{{ amt +1 }}</option>
</select>
Because the design doesn't allow for labels on form elements, the label is essentially the first option in the select element. I want this control to be invalid unless it matches the following pattern: /^[0-9]$/.
I have tried using ng-pattern on the <select> however that doesn't seem to have any effect, Angular always thinks the control is valid.
The only other way I can think of doing it is writing a function in my controller to check if this control is valid and block the form from submitting if it's not. But I don't want to introduce a random validation function into my nice clean controller.
What's the best way to deal with this?

You can use the ng-options attribute here, rather than ng-repeat, and attribute a blank value to any options you wish to ignore. For example:
<select name="noOfPeople" ng-model="noOfPeople" ng-options="value for value in [] | range:12">
<option value="">No of people*</option>
<option value="">This won't count either!</option>
</select>
<p>Selected Value: {{noOfPeople}}<p>
If you explicitly require the regex checking to occur, you could write a filter and add it to the ng-options.

Related

Angular 2 Select Dropdown not Binding after Default value provided

This is my Angular 2 Code:
HTML:
<select class="form-control" [(ngModel)]="wrapupData.assignToEmployee">
<option value="" disabled>Choose Status</option>
<option *ngFor="let emp of masterWrapupLov.employeeList"
[value]='emp.id'>{{emp?.name}}</option>
</select>
where wrapupData.assignToEmployee is a string, masterWrapupLov.employeeList is an array of Objects comprising id: string and name: string.
This code works perfectly fine selecting the option to make it reflect in the wrapupData.assignToEmployee model.
What I wanted to achieve is to select a default option when loading the DOM and update the model if the option is changed. I tried using [selected] comparing emp.id with the value I wanted to select, it did work in the UI but is not getting binded with the model as and when I change it. I tried using a default value using the model, that too is not working as it should and is not getting binded after the first default binding. I don't know if I'm clear enough, but I tried many methods that people have already suggested but nothing seems to work.

Want to add none as value in select multiple

I am using chosen.jquery.js for select field
<select chosen multiple data-placeholder="Select Body Part(s)"
ng-options="option.Name as option.Name for option in BodyPartList" ng-model="Body_Part">
<option value="" disabled>Select Body Part(s)</option>
</select>
But It shows only data-placeholder value in case of no data in model.
I want to show "Select Body Part(s)" as a option in list.
And user must not select this. Reason is that, I want to add dynamic "Unknown" value in list of Body_Parts. But it not reflect in list.
Same work for select having single selection.
I'm not seeing any problems with your code, as such. Like, I'm trying it and getting the visual behaviour I think you're wanting? Am I missing something?
Html just yours with ng-app etc, javascript is:
var myApp = angular.module('myApp', ['localytics.directives']);
myApp.controller('MyController', function($scope) {
$scope.BodyPartList = [
{ Name: "Arm" },
{ Name: "Leg" }
];
$scope.Body_Part = [];
});
Not sure if data-placeholder is actually doing anything.
Fiddle: http://jsfiddle.net/7187f6d9/
That said, it's not "working". In the fiddle I put a regular select box alongside the chosen one, and the chosen one doesn't seem to be writing to the ng-model correctly. I'm not sure what's up with that.
You can choose the below option
https://harvesthq.github.io/chosen/#optgroup-support
or push another item to the top of the array from server side as your custom label and disable it on client side with the help of ng-if and $index properties of ng-repeat and angularjs. If this make sense then its fine else i can give you a demo.
I hope your query is, you want show a place holder as current selected value but user shouldn't be able to select it.
Instead of making it disabled, make ithidden. Then display an error if a user doesn't select any other options, using the value of placeholder option.
A sample snippet is added below. If value of select is Error, write a case to throw a error back to user.
<select>
<option value="Error" hidden>Select any Company</option>
<option value="Toyota">Toyota</option>
<option value="Nissan">Nissan</option>
<option value="BMW">BMW</option>
</select>
Hope this helps! If not, ping me with your query. :)

Using a ONE WORD javascript variable in form field VALUES

I have a function that gets values from a the URL and then posts it to various places on the page.
I can't figure out how to get the values to read inside form field values.
<OPTION Value="<script type="text/javascript">document.write(Position)
</script> has final say">
I know I can't do that specifically, but I've tried various configurations and nothing posts the variable inside the value field.
The document.write function is working on the plain html, I have tested that. I just don't know to make it read inside a form field value and display the results properly.
How do I get one word to display as a variable, without having to create a function that inputs the value of each field. There are way too many fields to make that viable - this needs to populate into maybe 200 or 300 variables, so I really need it to be the word.
The site is standalone so I can't use php as I understand it. If there's a way I'm open to it. I did try the php echo to call the field name but I don't know enough about php to know if I'm missing something.
I am open to solutions where I can upload files into the standalone site though.
Thanks in advance.
Is this what you're looking for?
var position = 'helloworld'
document.getElementById('id1').options[0].value=position;
<select id="id1">
<option>The Value is the POSITION variable.</option>
</select>
I added an ID to the select box (<select id="id1">). Then you can use the script to insert the position variable as the value of the options within the select.
If this is not what you're looking for then you really need to update your question with more sample from your code (i.e some HTML would be nice).
If you are stuck writing code only on the client-side, then you may want to use a client-side library like jQuery to help you manage your DOM manipulation.
For example, you can set a class for every variable you want to set and then use jQuery to replace the contents of those elements.
var values = {
position: "top",
name: "steve"
}
$(".position").text(values.position).val(values.position)
$(".name").text(values.name).val(values.name)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option class="position"></option>
<option class="name"></option>
</select>
<select>
<option class="name"></option>
</select>
<select>
<option class="position"></option>
</select>
<select>
<option class="position"></option>
<option class="name"></option>
<option class="position"></option>
<option class="name"></option>
</select>

How to get the selected value of some random dropdown in Javascript/jQuery

<select ng-model="myModel" id="searchAsset" class="search">
<option ng-repeat="asset in assettype" ng-click="assetclick()" value="{{asset}}"></option>
</select>
<select class="search" id="searchLevel">
<option class="chooseLevel" ng-repeat="level in levellist" value="{{level}}"></option>
</select>
While performing some logic on second dropdown, I want to fetch the selected value of the first dropdown or vice-versa. How can I do this?
I tried using $("#searchLevel").value and $("#searchLevel option:selected").text()
The direct answer to this question is to use the .val() method for jQuery like so:
var selectedVal = $("#searchLevel").val();
However, the slightly less direct, but true answer is that you should not be doing anything like this in an angular app - changes in the dom should only be affecting your view model.
When your using angular, jquery is really not required.
As per your code, The first select menu value will be stored in the ng-model attribute value i.e. myModel.
In your second select menu, specific the ng-model as well. You can just fetch the value of the drop down menu by calling ng-model name.
<select class="search" id="searchLevel" ng-model="secondSelect">
<option class="chooseLevel" ng-repeat="level in levellist" value="{{level}}"></option>
</select>
For example,
If you want to access the value inside your controller on change event, then
$scope.changeEventhandlerForFirstSelect = function() {
// $scope.myModel will contain the value
}
Similarly, for second select menu $scope.secondSelect will give that value.
try
$("#searchLevel").val();
with: $("#searchLevel option:selected").text() you get the text not the value.

AngularJS selecting multiple options

So, What I'm trying to do is fairly simple with vanilla JS, but I'm using AngularJS and I would like to know how to do it the best way within the framework. I want to update the selected options in a multiple select box. I do not want to add or remove any of the options. Here is what my HTML looks like:
<select multiple>
<option value="1">Blue</option>
<option value="2">Green</option>
<option value="3">Yellow</option>
<option value="4">Red</option>
</select>
Using the following array, I'd like to programmatically select/deselect options from this list:
[{id:1, name:"Blue"},{id:4, name:"Red"}]
When I set this array in the scope, I want the select box to deselect anything that is not Blue or Red and select Blue and Red. The standard response that I've seen on the Google Groups is to use ng-repeat. However, I can't recreate the list every time because the list of selected values is incomplete. As far as I can tell, AngularJS has no mechanism for this, and I'm at a loss as to how I would do this without resorting to using jQuery.
ngModel is pretty awesome! If you specify the indexes as a model selectedValues
<select multiple ng-model="selectedValues">
built from your list (selected) in a $watch
$scope.$watch('selected', function(nowSelected){
// reset to nothing, could use `splice` to preserve non-angular references
$scope.selectedValues = [];
if( ! nowSelected ){
// sometimes selected is null or undefined
return;
}
// here's the magic
angular.forEach(nowSelected, function(val){
$scope.selectedValues.push( val.id.toString() );
});
});
ngModel will automatically select them for you.
Note that this data binding is one-way (selected to UI). If you're wanting to use the <select> UI to build your list, I'd suggest refactoring the data (or using another $watch but those can be expensive).
Yes, selectedValues needs to contain strings, not numbers. (At least it did for me :)
Full example at http://jsfiddle.net/JB3Un/

Categories

Resources