I have HTML form with set of elements(inputs).
So, how to detect changes in any input and set new statement in object var data?
For example:
<input type="text" name="parameter" value="30">
When I make chnages in input I need to get output object data as:
var = data = ["paraeter" : 30];
for watch the value on change in angular you should use ng-change and ng-model
var app = angular.module("app", []).
controller("ctrl", function($scope) {
$scope.info = {
parameter: 30,
parameters: {
children: 40
}
};
$scope.callBackIfChange = function(){
console.log($scope.info);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<form>
<label>empty value</label>
<input type="text" ng-model="info.name" ng-change="callBackIfChange()">
<br>
<br>
<label>has default value</label>
<input type="number" ng-model="info.parameter" ng-change="callBackIfChange()">
<br>
<br>
<label>nested</label>
<input type="number" ng-model="info.parameters.children" ng-change="callBackIfChange()">
</form>
<hr>
<b>output:</b> {{info | json}}
</div>
Here is the Jquery code covering your cases (onload and input change) without hard-coding the name attributes of inputs tags:
var inputValuesObj = {}; // << Your Object
$(document).ready(function() {
getDefaultInputValues();
});
$(document).on("load keyup", "input", function() {
getDefaultInputValues();
});
function getDefaultInputValues() {
$("input").each(function(index) {
inputValuesObj[$(this).attr("name")] = $(this).val();
});
$("div#res").html(JSON.stringify(inputValuesObj));
}
Your test here - https://jsfiddle.net/uo08fedh/20/
Hope it helps!
Related
I got a requirement to bind a value to a particular model when the value in the other model contains a string starting with "https".
For example, I have two text fields both fields having different model
<input type="text" ng-model="modelText1">
<input type="text" ng-model="modelText2">
Suppose I type a value on the first text field "https", the first input model modelText1 have to bind to the second input model modelText2 and later on i have to maintain it as like two-way binding. i.e. the second field will automatically get the value dynamically when it contains "https" at starting of a string.
Try it like in this Demo fiddle.
View
<div ng-controller="MyCtrl">
<input type="text" ng-model="modelText1">
<input type="text" ng-model="modelText2">
</div>
AngularJS Application
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
$scope.modelText1 = '';
$scope.modelText2 = '';
var regEx = new RegExp(/^https/);
$scope.$watch('modelText1', function (newValue) {
if (newValue.toLowerCase().match(regEx)) {
$scope.modelText2 = newValue;
} else {
$scope.modelText2 = '';
}
});
});
An other approach is (that avoid using of $watch) is to use AngularJS ng-change like in this
example fiddle.
View
<div ng-controller="MyCtrl">
<input type="text" ng-model="modelText1" ng-change="change()">
<input type="text" ng-model="modelText2">
</div>
AngularJS Application
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
$scope.modelText1 = '';
$scope.modelText2 = '';
var regEx = new RegExp(/^https/);
$scope.change = function () {
if ($scope.modelText1.toLowerCase().match(regEx)) {
$scope.modelText2 = $scope.modelText1;
} else {
$scope.modelText2 = '';
}
};
});
You can use the ng-change directive like this:
<input type="text" ng-model="modelText1" ng-change="onChange()">
<input type="text" ng-model="modelText2">
and your controller:
$scope.onChange = function() {
if ($scope.modelText1 === 'https') {
$scope.modelText2 = $scope.modelText1;
else
$scope.modelText2 = '';
};
use ng-change to check the text is equal to 'https'
angular.module('app',[])
.controller('ctrl',function($scope){
$scope.changeItem = function(item){
$scope.modelText2 = "";
if(item.toLowerCase() === "https"){
$scope.modelText2 = item
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input type="text" ng-model="modelText1" ng-change="changeItem(modelText1)">
<input type="text" ng-model="modelText2">
</div>
EDiTED
to make sure it does't fail under 'HTTPS' use toLoweCase function to make all lower case
HTML :
<input type="text" ng-model="modelText1" ng-change="updateModal(modelText1)">
JS :
var modelText1 = $scope.modelText1.toLowerCase();
$scope.updateModal = function(){
$scope.modelText2 = '';
if(modelText1.indexOf('https')!=-1){
$scope.modelText2 = modelText1;
}
}
you could also possibly do this as a directive if you want to have a more reusable solution over multiple views http://jsfiddle.net/j5ga8vhk/7/
It also keeps the controller more clean, i always try to use the controller only for controlling complex business logic and business data
View
<div ng-controller="MyCtrl">
<input type="text" ng-model="modelText1" >
<input type="text" ng-model="modelText2" model-listener="modelText1" model-listener-value="https" >
</div>
Angular JS
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
$scope.modelText1 = '';
$scope.modelText2 = '';
});
myApp.directive('modelListener', [function() {
return {
restrict: 'A',
controller: ['$scope', function($scope) {
}],
link: function($scope, iElement, iAttrs, ctrl) {
$scope.$watch(iAttrs.modelListener, function() {
if($scope[iAttrs.modelListener] === iAttrs.modelListenerValue ) {
$scope[iAttrs.ngModel] = $scope[iAttrs.modelListener];
} else {
$scope[iAttrs.ngModel] = "";
}
}, true);
}
};
}]);
I have written this code online dynamic form jsFiddle code
The total and grand total are not auto updating. I had a more simple example before and it was working with a single model item, but then I made an array and now it won't work. My real program I am building is going to have many more fields and I am trying to create a pre-example to show it will work. Can someone quickly see what dumb thing I am forgetting?
<div ng-controller="MyCtrl">
<form name="myForm">
<div ng-repeat="item in items track by $index">
<input type="text" ng-model="item.a">
<input type="text" ng-model="item.b">
<input type="text" ng-model="item.c">
<label>Total: </label><label ng-bind="total(item)"></label>
</div>
</form>
<div>
<label>Grand Total: </label><label ng-bind="grandTotal()"></label>
</div>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.items = [
{
a: 0, b: 0, c: 0
},
{
a: 0, b: 0, c: 0
}];
$scope.total = function(item) {
var result = item.a * item.b * item.c;
return isNaN(result) ? 0 : result;
};
$scope.grandTotal = function() {
var result = 0;
angular.forEach($scope.items, function(item) {
result += $scope.total(item);
});
return isNaN(result) ? "" : result.toString();
};
});
ng-bind should be without $scope. You don't need to mention $scope in view bindings, it directly refers to $scope/this(context) of controller.
Other than that additionally change all input's ng-bind to ng-model to enable two way binding over all input fields.
Markup
<input type="text" ng-model="item.a">
<input type="text" ng-model="item.b">
<input type="text" ng-model="item.c">
ng-bind="total(item)"
Forked JSFiddle
Use
<input type="text" ng-model="item.a">
instead of
<input type="text" ng-bind="item.a">
Updated fiddle http://jsfiddle.net/Lhkedykz/17/
I want to search the House Name from all the input the user provided.
so if the user details are as:
[{"houseName":"man","houseType":"villa","houseFloors":"seven","houselocation":"Seattle"},{"houseName":"band","houseType":"small","houseFloors":"two","houselocation":"washington DC"}]
If i provide search as man ,it should give me as:
[{"houseName":"man","houseType":"villa","houseFloors":"seven","houselocation":"Seattle"}]
The code is as :
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>House Name
<input type='text' name='houseName' id='houseName' placeholder="House Name">
</label>
<br>
<br>
<label>House type
<input type='text' name='houseType' id='houseType' placeholder="House type">
</label>
<br>
<br>
<label>House Floors:
<input type='text' name='houseFloors' id='houseFloors' placeholder="House Floors">
</label>
<br>
<br>
<label>House Location:
<input type='text' name='houselocation' id='houselocation' placeholder="House Location">
</label>
<br>
<br>
<div>
<label>search:
<input type="text" name="search" id="search-input" placeholder="search">
<input type="submit">
</div>
<button type="button" id="add">Add Details</button>
<button type="button" id="print">Show</button>
<pre></pre>
<script>
var list = [],
$ins = $('#houseName, #houseType, #houseFloors, #houselocation'),
var counter = {
houseName: {},
houseType: {},
houseFloors: {},
houselocation: {}
};
$('#add').click(function() {
var obj = {},
valid = true;
$ins.each(function() {
var val = this.value;
if (val) {
obj[this.id] = val;
} else {
alert(" Cannot be blank");
return false;
}
});
if (valid) {
list.push(obj);
$ins.val('');
}
});
$('#print').click(function() {
$('pre').text(JSON.stringify(list) + '\n\n');
})
var keyword = $('#search-input').val();
var filteredList = list.filter(function(user){
return user.houseName === 'man'; // Or u can use indexOf if u want check if the keyword is contained
});
</script>
</body>
</html>
You may use Array.prototype.filter.
In ur case it will look like
var filteredList = list.filter(function(user){
return user.houseName === 'man'; // Or u can use indexOf if u want check if the keyword is contained
});
If u would like to search it with an input box, there will be a little bit more work to do:
//The follow code should be executed when u are going to do the 'search' action
//It could be an click on a button, or just in a listener which is triggered when the search box fires 'change' events
//First u need to get the keyword from the search input box:
var keyword = $('#search-input').val();
//maybe do some value check
//if (keyword === '') return;
//then get the filtered List
var filteredList = list.filter(function(user){
return user.houseName === keyword;
});
//Finally update the UI based on the filtered List
//Maybe jQuery's DOM functions could be helpful
I need to set the data-ng-model attribute of an html input field via javascript.
I know I can't do
element.data-ng-model = "...";
because of the dashes. So I tried
element.["data-ng-model"] = "...";
and
element.dataNgModel = "...";
and
element.datangmodel = "...";
None of these seem to work properly.
Any suggestions?
Try:
element.setAttribute("ng-model", "...");
or if you have JQuery:
$(element).attr("ng-model", "...");
If you need to set the model with javascript you can set it in the controller see below From the angular docs
https://docs.angularjs.org/api/ng/directive/ngModel
(function(angular) {
'use strict';
angular.module('getterSetterExample', [])
.controller('ExampleController', ['$scope',
function($scope) {
var _name = 'Brian';
$scope.user = {
name: function(newName) {
// Note that newName can be undefined for two reasons:
// 1. Because it is called as a getter and thus called with no arguments
// 2. Because the property should actually be set to undefined. This happens e.g. if the
// input is invalid
return arguments.length ? (_name = newName) : _name;
}
};
}
]);
})(window.angular);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<div ng-app="getterSetterExample">
<div ng-controller="ExampleController">
<form name="userForm">
<label>Name:
<input type="text" name="userName" ng-model="user.name" ng-model-options="{ getterSetter: true }" />
</label>
</form>
<pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>
</div>
Trying to auto-populate first input field value into second input field value, However if the second input field as existing values then i would like to append / concatenate the first input field value to second.
logic:
if ( second ){
second = first + second;
}else{
second = first;
}
html:
<input type='text' ng-model='owner' required class="form-control">
<input type='text' ng-model='member' required class="form-control">
code:
app.controller("Controller", ['$scope', function($scope){
$scope.$watch(function () {
return $scope.owner;
},
function (newValue, oldValue) {
if ( $scope.member ){
$scope.member = $scope.owner + ',' + $scope.member;
}else{
$scope.member = newValue;
}
}, true);
}]);
plunker
Update (problem):
When i type Jake in Owner Field, it loops through the letters and print's as Jake,Jak,Ja,Jin member field. If i have pre-existing value Adam in member field, upon entering Tom in owner filed it will create Tom,To,T,Adam in member field. Please check the plunker for demo.
Mad-D consider changing your approach as it is prone to a circular dependency based on the way ng-model works.
You already have access to both values and you can display it in other ways. Plus your controller looks cleaner and acts as a true view model (vm):
Plunker
app.controller("Controller", function(){
var myCtrl = this;
myCtrl.owner = "";
myCtrl.member = "";
});
I have created a plnkr
. And also given below. Check whether it's correct one for you.
var app = angular.module('form-example1', []);
app.controller("Controller", ['$scope', function($scope){
$scope.permaMember = $scope.member?$scope.member:'';
$scope.editSecond = function(member){
$scope.permaMember = member?member:'';
}
$scope.editFirst = function(owner){
if(owner){
$scope.member = $scope.permaMember + owner
}
else{
$scope.member = $scope.permaMember
}
}
}]);
<!doctype html>
<html ng-app="form-example1">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div ng-controller="Controller">
<form name="testform">
<div class='form-group'>
<label>Owner</label>
<input type='text' ng-model='owner' required class="form-control" ng-change="editFirst(owner)">
</div>
<div class='form-group'>
<label>Member</label>
<input type='text' ng-model='member' required class="form-control" ng-change="editSecond(member)">
</div>
<button ng-disabled="testform.$invalid" ng-click ="submit()">SAVE</button>
</form>
</div>
</body>
</html>
Why not just have a 3rd read only text box or label that displays $scope.owner, $scope.member?