ng-pattern not functioning in AngularJS - javascript

<label for="updateInterval" class="control-label" for="UpdateInterval">Select Interval</label>
<input name="intervalRange" id="intervalRange" ng-pattern="" type="number" class="form-control input-medium fld-updateinterval-val" placeholder="" ng-model="update_interval" ng-required="true" >
<select class="form-control input-medium sampleForm-combo" onchange="changetextbox(this.value)" id="action" ng-model="update_intervalSelect" ng-required="true">
<option></option>
<option value="days">days</option>
<option value="hours">hours</option>
</select>
Above I have an input box and a dropdown list where the value being inputted in the first text box depends on the value being chosen in at the dropdown list. The JavaScript is reading it well, but my problem is that ng-pattern is not functioning, and I don't know why. If I check it in Firebug, it is being shown that ng-pattern is placed into the textbox, but I'm not sure why I am still able to input numbers that are not within the range I have specified.
function changetextbox(interval)
{
if(interval == "days"){
$(".fld-updateinterval-val").attr("placeholder", "1-365");
$(".fld-updateinterval-val").attr("ng-pattern", "/\\b([1-9][0-9]?|[12][0-9]{2}|3[0-5][0-9]|36[0-5])\\b/");
}
else if (interval == "hours"){
$(".fld-updateinterval-val").attr("placeholder", "1-8760");
$(".fld-updateinterval-val").attr("ng-pattern", "/\\b([1-9][0-9]{0,2}|[1-7][0-9]{3}|8[0-6][0-9]{2}|87[0-5][0-9]|8760)\\b/");
}

Just adding ng-pattern as an attribute to input tag or changing it like above wont work. It requires to compile the element by $compile service in order to work properly.
Another simple way of achieving above thing is bind with some scope variable.
angular.module('textInputExample', [])
.controller('ExampleController', ['$scope',
function($scope) {
$scope.example = {
text: 'guest',
word: /[a-z]/,
changengpattern: function() {
this.word = /[0-9]/;
}
};
}
]);
HTML
<form name="myForm" ng-controller="ExampleController">
Single word:
<input type="text" name="input" ng-model="example.text" ng-pattern="example.word" required ng-trim="false">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.pattern">
Single word only!</span>
<tt>text = {{example.text}}</tt>
<br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt>
<br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt>
<br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt>
<br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt>
<br/>
<input type="button" value="click me to change ng pattern" ng-click="example.changengpattern()" />
</form>
Here is working fiddle for you

I had the same issues until I found out, that angular needs both starting and string-end tag within your regex.
Your examples then would look like:
$(".fld-updateinterval-val").attr("ng-pattern", "/^\\b([1-9][0-9]?|[12][0-9]{2}|3[0-5][0-9]|36[0-5])\\b$/");
$(".fld-updateinterval-val").attr("ng-pattern", "/^\\b([1-9][0-9]{0,2}|[1-7][0-9]{3}|8[0-6][0-9]{2}|87[0-5][0-9]|8760)\\b$/");
Pay attention to the pattern string starting with /^ and finishing up with $/. This solved my issues with custom ng-patterns.

ng-pattern= "/^([0-9][0-9]{0,2}|[1-7][0-9]{3}|8[0-6][0-9]{2}|87[0-5][0-9]\d|8760)$/"

provide the regex ("/\\b([1-9][0-9]?|[12][0-9]{2}|3[0-5][0-9]|36[0-5])\\b/") into the input where inside the ng-pattern.
For example,
ng-pattern="/\\b([1-9][0-9]?|[12][0-9]{2}|3[0-5][0-9]|36[0-5])\\b/"
It Worked for me....

Related

Angular using ng-model in input field get null

I know how to pass a value from a view to a controller using ng-model. In the controller it just gets the value from the view using this code $scope.name = this.ngmodelnameinview.
Is it compulsory to use ng-model in field view?
but my problem now is, I have + button, which when I click the button it will automatically put the value inside input text field.
<button data-ng-click="adultCount = adultCount+1"> + </button>
<input type="text" name="totTicket" value="{{adultCount}}">
see picture below:
but when I add ng-model inside input field, it returns null
<input type="text" name="totTicket" value="{{adultCount}}" ng-model="adultcount">
How to fix this? Thanks!
It is giving null just because you have set a value "adultCount" and in ng-model you had given a different name "adultcount" ('c' is in lower case). By updating ng-model with "adultCount", will solve this issue.
JavaScript is case sensitive:
JavaScript is case-sensitive and uses the Unicode character set.1
Use the same case for the scope variable. Update the input attribute ng-model to match the varible - i.e.:
<input type="text" name="totTicket" value="{{adultCount}}" ng-model="adultcount">
should be:
<input type="text" name="totTicket" value="{{adultCount}}" ng-model="adultCount">
<!-- ^ -->
See this demonstrated in the snippet below:
angular.module('app', [])
.controller('ctrl', function($scope) {
//adultCount could be initialized here
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<button data-ng-click="adultCount = adultCount+1"> + </button>
totTicket:
<input type="text" name="totTicket" value="{{adultCount}}">
totTicket (adultCount):
<input type="text" name="totTicket" value="{{adultCount}}" ng-model="adultCount">
</div>
——
1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types

Get HTML element data in AngularJS script

I am new to AngularJS and trying to design a page which will have two text fields and two radio buttons.
First text field is for current address, followed by radio buttons(one for Yes and second for No), and last component would be permanent address text field. First, user will enter the value in current address text field, after that if user selects yes radio button then it should copy the data from current address to permanent address text field, if user selects No then it should do nothing. Below is the sample code I have written:
*<input type="text" name="cAddress" ng-model="cAddress" required/>
<input type="radio" name="opt" ng-click="copyAddress(true)" />
<input type="radio" name="opt" ng-click="copyAddress(false)" />
<input type="text" name="pAddress" ng-model="pAddress" required/>*
Below is the script code inside controller:
$scope.copyAddress = function(flag) {
if(flag) {
$scope.pAddress = $scope.cAddress;
}
};
when I tried to print $scope.cAddress and $scope.pAddress values in console then it displayed undefined. Even $scope does not have cAddress and pAddress.
Therefore, the main problem is that I am not getting element data inside AngularJS controller
Please find plunker url:
http://plnkr.co/edit/Ub2VEn01HxwDpnCg4tLi?p=preview
Click on Next to navigate to Second tab, there you will find the yes and no radio button to copy the data.
I have minized the code, please look into it. To understand the flow, you can read the README file.
http://plnkr.co/edit/TzJsZIRxAyTuFdCXLFFV?p=preview
Try using another scope object.
That is, create a scope object and add property to it for each input like,
$scope.myObject = {}; // Empty scope variable
$scope.myObject.cAddress = ""; // initialize your model for the input.
And now you should use this variable for your input.
<input type="text" name="cAddress" ng-model="myObject.cAddress" required/>
Try this. It may help you.
Html code:
<body ng-controller='Maincontroller'>
<input type="text" name="cAddress" ng-model="cAddress" />
<input type="radio" name="opt" ng-click="copyAddress(true)" />
<input type="radio" name="opt" ng-click="copyAddress(false)" />
<input type="text" name="pAddress" ng-model="pAddress" />
</body>
Controller code:
var app = angular.module('main', []);
app.controller('Maincontroller', ["$scope",
function($scope) {
$scope.copyAddress = function(flag) {
if (flag) {
$scope.address1 = $scope.address;
} else {
$scope.address1 = "";
}
};
}
]);

Set ng-model value to button click

I have this little snippet of code to set the root.lowWeight and root.highWeight to my controller.
<input type="number" placeholder="Enter Low Range..." class="form-control input-xs">
<input type="number" placeholder="Enter High Range..." class="form-control input-xs">
<button class="btn btn-primary" ng-click="assignWeights()">Select Model</button>
Controller model:
//set the initial root scope to empty object
$scope.root = {};
//define root weight
$scope.root.lowWeight = 0;
$scope.root.highWeight = 0;
I know I could just use ng-model="root.lowWeight" to set the value, but ng-model triggers on element input event.
How can I either:
a) Send the input values in via assignWeights(param1, param2)
b) Change ng-model to trigger input on button click (seems hacky, less preferred solution)
I also know I could use JS/jQuery to trigger the input event and block the input event, but that's a last ditch effort I will 99.9% not do.
Solution using seperate scope object: plunkr
Html:
Low: <input type="text" name="lowRange" ng-model="inputData.lowWeight">
High: <input type="text" name="highRange" ng-model="inputData.highWeight">
Js:
$scope.assignWeights = function() {
$scope.lowWeight = $scope.inputData.lowWeight;
$scope.highWeight = $scope.inputData.highWeight
}
In your assignWeights function, you could use a selector to retrieve the values of the inputs and then assign your scope variable values based on that. Just assign a name to each input.
E.g.
<input type="number" placeholder="Enter Low Range..." class="form-control input-xs" name="lowRange">
<input type="number" placeholder="Enter High Range..." class="form-control input-xs" name="highRange">
<button class="btn btn-primary" ng-click="assignWeights()">Select Model</button>
Controller:
$scope.assignWeights = function() {
$scope.root.lowWeight = document.querySelector('input[name="lowRange"]').value
$scope.root.highWeight = document.querySelect('input[name="highRange"]').value
}
Plunker: http://plnkr.co/edit/lm8GFA0CD0zWwgAMSLah?p=preview

AngularJS: ng-model not clearing input

I have a dynamic input for CPFs (Brazilian 'social security' number).
Every time I enter one CPF, another input should be displayed, and so on..
But for some reason, the ng-model is not being cleared after the CPF is added.
Here's my HTML (inside a directive with isolate scope):
<div ng-repeat="cpf in cpfs" class="field-input">
<input type="text" class="field" ng-model="cpf.number" required>
<label>added CPF</label>
</div>
<div class="field-input">
<input type="text" class="field" ng-model="cpf.number" required>
<label>add new CPF</label>
<button ng-click="addCpf(cpf)" class="btn btn-primary">add</button>
</div>
Here's my controller (inside a directive with isolate scope):
$scope.cpfs = [];
$scope.addCpf = function(cpf) {
$scope.cpfs.push(angular.copy(cpf));
delete $scope.cpf;
};
instead of delete $scope.cpf; use $scope.cpf.number = "";
we can't delete an model, we have to set it to blank, because its linked with our View part

show form value in alert after click on button

I am very new on HTML. I just trying to accept form value and want to show this value
in Alert. I try following code but it didn't help me...
I know this is very easy question but i am newbie on HTML,JavaScript. I search but didn't find relative to my requirement....
Javascript function....
function updateTxt(field1,field2)
{
var field1 = document.getElementById(field1);
var field2 = document.getElementById(field2);
alert(field1,field2);
}
HTML form
<input name="textfield" type="text" id="textfield" value="Search by keyword" class="search_input" >
<select name="select" id="select" class="input_list" >
<option>Search jobs by category</option>
<option>Business Sales Leadership Development Program</option>
<option>Business Sales Solutions</option>
<option>CTO</option>
<option>Call Center</option></select>
<input name="button" type="button" class="btn" value="Go" onClick="updateTxt(select,textfield)">
Please give me hint or direct me where i wrong...
Thanks in Advance
change this code
<input name="button" type="button" class="btn" value="Go" onclick="updateTxt()">
and also this
function updateTxt()
{
var field1 = document.getElementById('textfield').value;
var field2 = document.getElementById('select').options[document.getElementById('select').selectedIndex].value;
alert(field1+'&'+field2);
}
You need to pass strings into the updateTxt function. And alert can only take one parameter, so you'll have to concatenate the values of the fields, not the fields themselves. Your code would look like this:
JS:
function updateTxt(field1,field2)
{
var field1 = document.getElementById(field1).value;
var field2 = document.getElementById(field2).value;
alert(field1 + '\n' + field2);
} ​
HTML:
<input name="textfield" type="text" id="textfield" value="Search by keyword" class="search_input" >
<select name="select" id="select" class="input_list" onkeyup="updateTxt('select','txt2');">
<option>Search jobs by category</option>
<option>Business Sales Leadership Development Program</option>
<option>Business Sales Solutions</option>
<option>CTO</option>
<option>Call Center</option></select>
<input name="button" type="button" class="btn" value="Go" onClick="updateTxt('select', 'textfield')">​
Demo
You will need to change the onClick to:
onclick="updateTxt('select','textfield');
because when you are using reserved words in JS it is not good - to say the least ;)
For full list of reseved words: http://www.javascripter.net/faq/reserved.htm
You can see there 'select'.
Btw, you might want to change the names to something better and avoid 'onClick' and JS inside your html.
Good luck.
Your code does not have an element with the id 'txt2'. Also try to use more explicit IDs, like 'myTextField' instead of 'select', it will make it easier to read and maintain your code.
Other than that, Amaan's answer should work.

Categories