Setting an input's tabIndex dynamically - javascript

I have a form in my Angular app where users can enter in multiples of the same field values using an add button.
<md-content layout-padding="">
<div>
<form name="userForm">
<div layout="row" ng-repeat="person in persons">
<md-input-container flex>
<label>First name</label>
<input ng-model="person.firstName">
</md-input-container>
<md-input-container flex>
<label>Last Name</label>
<input ng-model="person.lastName">
</md-input-container>
</div>
<md-button class="md-raised" ng-click="addAnother()">Add Another</md-button>
</form>
</div>
</md-content>
Working Codepen
So already a couple of inputs are populated, clicking the button adds a new object in order for a new set of inputs to appear.
What I would like is for the first input on the newly added row to receive focus so the user can start entering in right away.
Is there some way to set the tabIndex programatically?

Check this out. The great answer on your question you can find here: Input autofocus attribute
angular.module('ng').directive('ngFocus', function($timeout) {
return {
link: function ( scope, element, attrs ) {
scope.$watch( attrs.ngFocus, function ( val ) {
if ( angular.isDefined( val ) && val ) {
$timeout( function () { element[0].focus(); } );
}
}, true);
element.bind('blur', function () {
if ( angular.isDefined( attrs.ngFocusLost ) ) {
scope.$apply( attrs.ngFocusLost );
}
});
}
};
});
<input type="text" ng-focus="isFocused" ng-focus-lost="loseFocus()">

I have noticed you make use of a class named md-input-focused
Method 1(the best)
This is the most simplest & elegant solution to your problem. Making use of $last in angular. Add a class condition on your <md-input-container> First name Codepen like so:
<md-input-container flex ng-class="{'md-input-focused': $last}">
<label>First name</label>
<input ng-model="person.firstName">
</md-input-container>
This method requires no additional javascript changes, but will only add the focus & not make the input active. See below method if you want to make the input active.
Method 2
Check the codepen. This is the same, but the javascript way of adding the same class dynamically
FYI: JQuery needed for the below statement. Hope you have that.
This is your magic statement. Codepen
$('.layout-row:last-of-type').children().first().find('input').focus();
Add this onto your $scope.addAnother function inside a timeout(very important).
Your whole function should look like
$scope.addAnother = function() {
$scope.persons.push({});
setTimeout(function(){
$('.layout-row:last-of-type').children().first().find('input').focus();
}, 500);
}
You could even make use of the angular $timeout instead of the window setTimeout

Here you go - CodePen
Markup
<input ng-model="person.firstName" auto-focus="true">
Directive
// Inspired by Mark Rajcok's answer - http://stackoverflow.com/a/14837021/782358
.directive('autoFocus', function($timeout) {
return {
scope: { trigger: '#autoFocus' },
link: function(scope, element) {
scope.$watch('trigger', function(value) {
if (value.toString() === "true") {
$timeout(function() {
element[0].focus();
});
}
});
}
};
});

Related

Angular access to generic ID

I have some code which adds new input and I need after some time for example 3 seconds input to hide. Problem is how to hide each separate input after 3 seconds of display each.
In html code I have:
id="{{ 'inputNum-' + $id }}"
In Javascript:
$timeout(function () {
document.getElementsById('commentNum-' + $id).css('display', 'none');
}, 3000);
https://jsfiddle.net
If you really want to manipulate DOM, the AngularJS-way to do this is to write your custom directive:
(function(){
'use strict';
angular
.module('inputsApp', [])
.controller('InputsController', InputsController)
.directive('hideMe', ['$timeout', function ($timeout) {
return {
link: function (scope, element, attrs) {
var timeOut = $timeout(function () {
angular.element(element).css('display', 'none');
}, new Number(attrs.hideMe));
scope.$on('$destroy', function(){
if (timeOut) $timeout.cancel(timeOut);
});
}
}
}])
InputsController.$inject = ['$scope', '$timeout'];
function InputsController($scope, $timeout) {
var vm = this;
// Current input.
vm.input = {};
// Array where inputs will be.
vm.inputs = [];
// Run when input is submited.
vm.addInput = function() {
vm.inputs.push( vm.input );
vm.input = {};
// Reset clases of the form after submit.
$scope.form.$setPristine();
}
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="inputs-app" ng-app="inputsApp" ng-controller="InputsController as cmntCtrl">
<div class="inputs">
<!-- Comment -->
<div class="input" hide-me="2000" ng-repeat="input in cmntCtrl.inputs" id="{{ 'inputNum-' + $id }}">
<!-- Comment Box -->
<div class="input-box">
<div class="input-text">{{ input.text }}</div>
</div>
</div>
</div>
<!-- From -->
<div class="input-form">
<form class="form" name="form" ng-submit="form.$valid && cmntCtrl.addInput()" novalidate>
<div class="form-row">
<textarea
class="input"
ng-model="cmntCtrl.input.text"
placeholder="Add input..."
required></textarea>
</div>
<div class="form-row">
<input type="submit" value="Add input">
</div>
</form>
</div>
</div>
I would use Angular's binding system.
add a property
vm.showCommentBox = true;
change to set the boolean
$timeout(function () {
vm.showCommentBox = false;
}, 3000);
add the binding to your html
<div class="input-box" ng-if="showCommentBox">
You need to think Angular way here: instead of modifying the UI directly, modify the model instead - and let framework do work for you. For example:
vm.addInput = function() {
var inputToAdd = vm.input;
vm.inputs.push(inputToAdd);
$timeout(function () {
var indexOfInput = vm.inputs.indexOf(inputToAdd);
vm.inputs.splice(indexOfInput, 1);
}, 3000);
vm.input = {};
// ... the rest of code
}
Demo. And if you don't actually those inputs to be dropped from the list, again, modify their attributes.
JS:
$timeout(function () {
var indexOfInput = vm.inputs.indexOf(inputToAdd);
vm.inputs[indexOfInput].hidden = true;
}, 3000);
Template:
<div class="input" ng-hide="input.hidden"
ng-repeat="input in cmntCtrl.inputs" id="{{ 'inputNum-' + $id }}">
Demo. With this approach, all the items are still in DOM (so it's exactly equivalent to what you tried to do). You might probably prefer using ng-if instead of ng-hide, dropping them from DOM completely.
General advice with Angular is doing things Angular way (it's convention over configuration framework).
And the Angular way would be to bind visibility with ng-show and ng-hide or existence in DOM via ng-if and then MODIFY THE MODEL NOT influence the DOM directly.
Alternatively, you can alter between element having a class and not with ng-class. And then separate styling in CSS file.
Depending on what you need: (choose class names yourself)
.hidden{
visibility: hidden;
}
or
.not-displayed{
display: none;
}

Vue JS focus next input on enter

I have 2 inputs and want switch focus from first to second when user press Enter.
I tried mix jQuery with Vue becouse I can't find any function to focus on something in Vue documentation:
<input v-on:keyup.enter="$(':focus').next('input').focus()"
...>
<input ...>
But on enter I see error in console:
build.js:11079 [Vue warn]: Property or method "$" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in anonymous component - use the "name" option for better debugging messages.)warn # build.js:11079has # build.js:9011keyup # build.js:15333(anonymous function) # build.js:10111
build.js:15333 Uncaught TypeError: $ is not a function
You can try something like this:
<input v-on:keyup.enter="$event.target.nextElementSibling.focus()" type="text">
JSfiddle Example
Update
In case if the target element is inside form element and next form element is not a real sibling then you can do the following:
html
<form id="app">
<p>{{ message }}</p>
<input v-on:keyup.enter="goNext($event.target)" type="text">
<div>
<input type="text">
</div>
</form>
js
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!',
focusNext(elem) {
const currentIndex = Array.from(elem.form.elements).indexOf(elem);
elem.form.elements.item(
currentIndex < elem.form.elements.length - 1 ?
currentIndex + 1 :
0
).focus();
}
}
})
JSFiddle Example
Following up from #zurzui here is in my opinion a cleaner alternative using the $refs API (https://v2.vuejs.org/v2/api/#vm-refs).
Using the $refs API, can allow you to target element in a simpler fashion without traversing the DOM.
Example: https://jsfiddle.net/xjdujke7/1/
After some tests, it's working
new Vue({
el:'#app',
methods: {
nextPlease: function (event) {
document.getElementById('input2').focus();
}
}
});
<script src="https://vuejs.org/js/vue.js"></script>
<div id='app'>
<input type="text" v-on:keyup.enter="nextPlease">
<input id="input2" type="text">
</div>
directives: {
focusNextOnEnter: {
inserted: function (el,binding,vnode) {
let length = vnode.elm.length;
vnode.elm[0].focus();
let index = 0;
el.addEventListener("keyup",(ev) => {
if (ev.keyCode === 13 && index<length-1) {
index++;
vnode.elm[index].focus();
}
});
for (let i = 0;i<length-1;i++) {
vnode.elm[i].onfocus = (function(i) {
return function () {
index = i;
}
})(i);
}
}
}
}
// use it
<el-form v-focusNextOnEnter>
...
</el-form>
Try this:
<input ref="email" />
this.$refs.email.focus()
Whilst I liked the directives answer due to it working with inputs inside other elements (style wrappers and so on), I found it was a little inflexible for elements that come and go, especially if they come and go according to other fields. It also did something more.
Instead, I've put together the following two different directives. Use them in your HTML as per:
<form v-forcusNextOnEnter v-focusFirstOnLoad>
...
</form>
Define them on your Vue object (or in a mixin) with:
directives: {
focusFirstOnLoad: {
inserted(el, binding, vnode) {
vnode.elm[0].focus();
},
},
focusNextOnEnter: {
inserted(el, binding, vnode) {
el.addEventListener('keyup', (ev) => {
let index = [...vnode.elm.elements].indexOf(ev.target);
if (ev.keyCode === 13 && index < vnode.elm.length - 1) {
vnode.elm[index + 1].focus();
}
});
},
},
},
On an enter key pressed, it looks for the index of the current input in the list of inputs, verifies it can be upped, and focuses the next element.
Key differences: length and index are calculated at the time of the click, making it more suitable for field addition/removal; no extra events are needed to change a cached variable.
Downside, this will be a little slower/more intensive to run, but given it's based off UI interaction...
Vue.js's directive is good practice for this requirement.
Define a global directive:
Vue.directive('focusNextOnEnter', {
inserted: function (el, binding, vnode) {
el.addEventListener('keyup', (ev) => {
if (ev.keyCode === 13) {
if (binding.value) {
vnode.context.$refs[binding.value].focus()
return
}
if (!el.form) {
return
}
const inputElements = Array.from(el.form.querySelectorAll('input:not([disabled]):not([readonly])'))
const currentIndex = inputElements.indexOf(el)
inputElements[currentIndex < inputElements.length - 1 ? currentIndex + 1 : 0].focus()
}
})
}
})
Note: We should exclude the disabled and readonly inputs.
Usage:
<form>
<input type="text" v-focus-next-on-enter></input>
<!-- readonly or disabled inputs would be skipped -->
<input type="text" v-focus-next-on-enter readonly></input>
<input type="text" v-focus-next-on-enter disabled></input>
<!-- skip the next and focus on the specified input -->
<input type="text" v-focus-next-on-enter='`theLastInput`'></input>
<input type="text" v-focus-next-on-enter></input>
<input type="text" v-focus-next-on-enter ref="theLastInput"></input>
</form>
<input type="text" #keyup.enter="$event.target.nextElementSibling.focus() />

Angular input inside of directive

I have an angular directive that I'm building with some pagination controls.
<div>
<!-- table logic here -->
</div>
<div>
<button bg-click="current=prevPage(current);">Prev</button>
<input ng-model="current" />
/{{pages}}
<button bg-click="current=nextPage(current);">Next</button>
</div>
It works fine, but of course when you change the value in the input.
It will also pick up the empty string during the delete before you enter a new value in.
Is there a way to sniff that out in the directive before it actually fires the change in the current value.
You can just check the value of the variable current before do pagination.
I assumes that you are using $watch() to listen the change of your variable current.
code inside your directive's link,
scope.$watch("current", function(newVal, oldVal){
if(angular.isNumber(newVal)){
// your variable is a number
// Do your pagination here
}
});
ngModelOptions is useful in such a case. You could write like this
<input ng-model="current" ng-model-options="{ updateOn: 'default', debounce: {'default': 500, 'blur': 0} }" />
to delay update value to model 500ms in default and update immediately if lost focus.
That question also has been answered several times, so you should be able to find further information in the other questions.
UPDATE:
$scope.$watch(
function() {
return $scope.current;
}, function(oldVal, newVal) {
if (!newVal) {
$scope.current = oldVal
}
}
);
If oldVal is also null or an empty string, you could copy $scope.current to another scope variable (say $scope.savedCurrent) whenever newVal has a value and copy it back to $scope.current if not.
I maybe understand wrong your question.
This will update the model only when you click outside the input
<input ng-model="current" ng-model-options="{updateOn: 'blur'}" />
Or another way, when you change the input value it call a function who test if the new value is valid and set it in current.
Html :
<div>
<button bg-click="current=prevPage(current);">Prev</button>
<input type="number" ng-model="currentInput" ng-change="changeCurrent()" />
/{{pages}}
<button bg-click="current=nextPage(current);">Next</button>
</div>
Controller :
$scope.currentInput = $scope.current;
$scope.changeCurrent = function(){
if ($scope.currentInput!=""){
$scope.current = $scope.currentInput;
}
}

Angularjs form validation order

I have a simple html form containing regular text input. ng-minlength, ng-maxlength and ng-pattern angular built-in form input directives are set on the input.
Problem: ng-pattern check is applied before the length check by ng-minlength and ng-maxlength.
Question: how can I change the default check order: i.e. first check for the length, then apply pattern check?
Example:
<body ng-app>
<div>
<form name="myForm">
Name: <input name="name" type="text" ng-model="name" ng-minlength="3" ng-maxlength="16" ng-pattern="/^\w+$/"/>
<div ng-show="myForm.name.$dirty && myForm.name.$invalid">
<span ng-show="myForm.name.$error.pattern">Pattern error</span>
<span ng-show="myForm.name.$error.minlength || myForm.name.$error.maxlength">Length error</span>
</div>
<br/>
<input type="submit" value="Submit">
</form>
</div>
</body>
Current behavior:
enter "#" - see "Pattern error"
enter "###" - see "Pattern error"
Desired behavior:
enter "#" - see "Length error"
enter "###" - see "Pattern error"
FYI, related jsfiddle.
Thanks in advance.
Write your own directive:
var mod = angular.module("myApp", []);
mod.directive("nameValidation", function () {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attrs, ngModelCtrl) {
var validate = function (value) {
var minLen = parseInt(attrs.myMinlength, 10),
maxLen = parseInt(attrs.myMaxlength, 10),
pattern = attrs.myPattern,
match = pattern.match(/^\/(.*)\/([gim]*)$/),
lenErr = false;
if (match) {
pattern = new RegExp(match[1], match[2]);
}
if (!ngModelCtrl.$isEmpty(value)) {
ngModelCtrl.$setValidity("pattern", true);
if ((minLen && value.length < minLen) || (maxLen && value.length > maxLen)) {
ngModelCtrl.$setValidity("length", false);
lenErr = true;
}
else {
ngModelCtrl.$setValidity("length", true);
lenErr = false;
}
if (!lenErr) {
if (match && !pattern.test(value)) {
ngModelCtrl.$setValidity("pattern", false);
}
else {
ngModelCtrl.$setValidity("pattern", true);
}
}
}
else {
ngModelCtrl.$setValidity("length", true);
ngModelCtrl.$setValidity("pattern", true);
}
}
ngModelCtrl.$parsers.push(validate);
ngModelCtrl.$formatters.push(validate);
}
}
});
Then in your HTML, include the app and use the directive:
<body ng-app="myApp">
<div>
<form name="myForm">
Name: <input name="name" type="text" ng-model="name" name-validation="" my-minlength="3" my-maxlength="16" my-pattern="/^\w+$/"/>
<div ng-show="myForm.name.$dirty && myForm.name.$invalid">
<span ng-show="myForm.name.$error.pattern">Pattern error</span>
<span ng-show="myForm.name.$error.length">Length error</span>
</div>
<br/>
<input type="submit" value="Submit">
</form>
</div>
</body>
The directive uses my-minlength, my-maxlength, and my-pattern for the three values. If length fails, that will trip first. If not, then pattern will show as error if it doesn't match. Consider renaming this directive if you want to use it other places besides name as minlength, maxlength, and pattern can be passed to it via attributes. If they are left off, they will be ignored.
See jsfiddle: http://jsfiddle.net/4zpxk/6/
I searched in angular code why this behavior. Then in the function 'textInputType' that it's the specific function that handles text inputs for the angular 'input' directive I found this at the end of this function, where we can see three blocks of code.
// pattern validator
if (pattern){
//validator logic
}
// min length validator
if (attr.ngMinlength) {
//validator logic
}
// max length validator
if (attr.ngMaxlength) {
//validator logic
}
So, no matter if you change the declaration order of your ng-* attributes in the html input element you will always get same result but if you change the order of the blocks, I mean, put the min length validator block before pattern validator block you will have the result that you expect.
This is a solution for your problem but you have to make a litte change in angular code and I don't know if you really like this. But you got a very common situation where order of the declaration of validation concepts matters, so, something more must be done to handle this. Thanks
You cannot change the default check order unfortunately.
One solution is to write a custom validator, not that difficult. Based on this answer, I came up with this code (fiddle)
Usage: There is an array of validation functions in the scope, they get passed to our custom directive "validators" as:
<input name="name" type="text" ng-model="name" validators="nameValidators"/>
A validator function would look like (e.g. for the minlength constraint):
function minlength(value, ngModel) {
if( value == null || value == "" || value.length >= 3 ) {
ngModel.$setValidity('minlength', true);
return value;
}
else {
ngModel.$setValidity('minlength', false);
return;
}
}
Important points are: it takes the value and the ngModel as arguments, performs the test (here value.length >= 3) and calls ngModel.$setValidity() as appropriate.
The directive registers the given functions with ngModel.$parsers:
app.directive("validators", function($parse) {
return {
restrict: "A",
require: "ngModel",
link: function(scope, el, attrs, ngModel) {
var getter = $parse(attrs.validators),
validators = getter(scope),
i;
for( i=0; i < validators.length; i++ ) {
ngModel.$parsers.push((function(index) {
return function(value) {
return validators[index](value, ngModel);
};
})(i));
}
}
};
});
Many details can be tweaked and improved, but the outline works (again link to fiddle). Now the order of validation is explicitly set by the order of the validator functions in the nameValidators array.
If you use ng-messages you should be able to set the order via the order of ng-message elements, e.g:
<div ng-messages="field.$error">
<ul class="validation-errors">
<li ng-message="required">This has the highest prio</li>
<li ng-message="min">Second in command</li>
<li ng-message="max">I'm last</li>
</ul>
</div>
Also the docs on this: https://docs.angularjs.org/api/ngMessages/directive/ngMessages
i just changed the order of your directives, pattern first
<input name="name" type="text" ng-model="name" ng-pattern="/^\w+$/" ng-minlength="3" ng-maxlength="16"/>
EDIT: uuum, tested your fiddel without changes and it shows your desired behavior ...
directives are compiled by priority, bbut i don't know how to set angulars directives priority ... sorry, should have tested this first

AngularJS does not send hidden field value

For a specific use case I have to submit a single form the "old way". Means, I use a form with action="". The response is streamed, so I am not reloading the page. I am completely aware that a typical AngularJS app would not submit a form that way, but so far I have no other choice.
That said, i tried to populate some hidden fields from Angular:
<input type="hidden" name="someData" ng-model="data" /> {{data}}
Please note, the correct value in data is shown.
The form looks like a standard form:
<form id="aaa" name="aaa" action="/reports/aaa.html" method="post">
...
<input type="submit" value="Export" />
</form>
If I hit submit, no value is sent to the server. If I change the input field to type "text" it works as expected. My assumption is the hidden field is not really populated, while the text field actually is shown due two-way-binding.
Any ideas how I can submit a hidden field populated by AngularJS?
You cannot use double binding with hidden field.
The solution is to use brackets :
<input type="hidden" name="someData" value="{{data}}" /> {{data}}
EDIT : See this thread on github : https://github.com/angular/angular.js/pull/2574
EDIT:
Since Angular 1.2, you can use 'ng-value' directive to bind an expression to the value attribute of input. This directive should be used with input radio or checkbox but works well with hidden input.
Here is the solution using ng-value:
<input type="hidden" name="someData" ng-value="data" />
Here is a fiddle using ng-value with an hidden input: http://jsfiddle.net/6SD9N
You can always use a type=text and display:none; since Angular ignores hidden elements. As OP says, normally you wouldn't do this, but this seems like a special case.
<input type="text" name="someData" ng-model="data" style="display: none;"/>
In the controller:
$scope.entityId = $routeParams.entityId;
In the view:
<input type="hidden" name="entityId" ng-model="entity.entityId" ng-init="entity.entityId = entityId" />
I've found a nice solution written by Mike on sapiensworks. It is as simple as using a directive that watches for changes on your model:
.directive('ngUpdateHidden',function() {
return function(scope, el, attr) {
var model = attr['ngModel'];
scope.$watch(model, function(nv) {
el.val(nv);
});
};
})
and then bind your input:
<input type="hidden" name="item.Name" ng-model="item.Name" ng-update-hidden />
But the solution provided by tymeJV could be better as input hidden doesn't fire change event in javascript as yycorman told on this post, so when changing the value through a jQuery plugin will still work.
Edit
I've changed the directive to apply the a new value back to the model when change event is triggered, so it will work as an input text.
.directive('ngUpdateHidden', function () {
return {
restrict: 'AE', //attribute or element
scope: {},
replace: true,
require: 'ngModel',
link: function ($scope, elem, attr, ngModel) {
$scope.$watch(ngModel, function (nv) {
elem.val(nv);
});
elem.change(function () { //bind the change event to hidden input
$scope.$apply(function () {
ngModel.$setViewValue( elem.val());
});
});
}
};
})
so when you trigger $("#yourInputHidden").trigger('change') event with jQuery, it will update the binded model as well.
Found a strange behaviour about this hidden value () and we can't make it to work.
After playing around we found the best way is just defined the value in controller itself after the form scope.
.controller('AddController', [$scope, $http, $state, $stateParams, function($scope, $http, $state, $stateParams) {
$scope.routineForm = {};
$scope.routineForm.hiddenfield1 = "whatever_value_you_pass_on";
$scope.sendData = function {
// JSON http post action to API
}
}])
I achieved this via -
<p style="display:none">{{user.role="store_user"}}</p>
update #tymeJV 's answer
eg:
<div style="display: none">
<input type="text" name='price' ng-model="price" ng-init="price = <%= #product.price.to_s %>" >
</div>
I had facing the same problem,
I really need to send a key from my jsp to java script,
It spend around 4h or more of my day to solve it.
I include this tag on my JavaScript/JSP:
$scope.sucessMessage = function (){
var message = ($scope.messages.sucess).format($scope.portfolio.name,$scope.portfolio.id);
$scope.inforMessage = message;
alert(message);
}
String.prototype.format = function() {
var formatted = this;
for( var arg in arguments ) {
formatted = formatted.replace("{" + arg + "}", arguments[arg]);
}
return formatted;
};
<!-- Messages definition -->
<input type="hidden" name="sucess" ng-init="messages.sucess='<fmt:message key='portfolio.create.sucessMessage' />'" >
<!-- Message showed affter insert -->
<div class="alert alert-info" ng-show="(inforMessage.length > 0)">
{{inforMessage}}
</div>
<!-- properties
portfolio.create.sucessMessage=Portf\u00f3lio {0} criado com sucesso! ID={1}. -->
The result was:
Portfólio 1 criado com sucesso! ID=3.
Best Regards
Just in case someone still struggles with this, I had similar problem when trying to keep track of user session/userid on multipage form
Ive fixed that by adding
.when("/q2/:uid" in the routing:
.when("/q2/:uid", {
templateUrl: "partials/q2.html",
controller: 'formController',
paramExample: uid
})
And added this as a hidden field to pass params between webform pages
<< input type="hidden" required ng-model="formData.userid" ng-init="formData.userid=uid" />
Im new to Angular so not sure its the best possible solution but it seems to work ok for me now
Directly assign the value to model in data-ng-value attribute.
Since Angular interpreter doesn't recognize hidden fields as part of ngModel.
<input type="hidden" name="pfuserid" data-ng-value="newPortfolio.UserId = data.Id"/>
I use a classical javascript to set value to hidden input
$scope.SetPersonValue = function (PersonValue)
{
document.getElementById('TypeOfPerson').value = PersonValue;
if (PersonValue != 'person')
{
document.getElementById('Discount').checked = false;
$scope.isCollapsed = true;
}
else
{
$scope.isCollapsed = false;
}
}
Below Code will work for this IFF it in the same order as its mentionened
make sure you order is type then name, ng-model ng-init, value. thats It.
Here I would like to share my working code :
<input type="text" name="someData" ng-model="data" ng-init="data=2" style="display: none;"/>
OR
<input type="hidden" name="someData" ng-model="data" ng-init="data=2"/>
OR
<input type="hidden" name="someData" ng-init="data=2"/>

Categories