Adding digits entered in input boxes with keyup event in angular js - javascript

I am looking to display the addition of four values entered in the input boxes
<td><input type="text" value="22" style="width:60px;margin:6px;" ng-keyup="getkeys($event)" ng-model="one"></td>
<td><input type="text" style="width:60px;margin:6px;" ng-keyup="getkeys($event)" ng-model="two"></td>
<td><input type="text" style="width:60px;margin:6px;" ng-keyup="getkeys($event)" ng-model="three"></td>
<td><input type="text" style="width:60px;margin:6px;" ng-keyup="getkeys($event)" ng-model="four"></td>
And this is my js
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.getkeys = function (event) {
if($scope.one==='' || $scope.two==='' || $scope.three==='' || $scope.four==="" )
{
$scope.one=parseInt("0");
$scope.two=parseInt("0");
$scope.three=parseInt("0")
$scope.four=parseInt("0")
}
$scope.keyval = parseInt($scope.one)+parseInt($scope.two)+parseInt($scope.three)+parseInt($scope.four);
console.log($scope.keyval);
}
});
what i want is as soon as someone enters the value in the input boxes ,sum of all the four gets displayed ,the problem is if firstly user enters value in any box it display NaN ,until all the four values are entered any idea how to achieve it?
And how to know which ng-model value has been entered ,just like this.value in js

This is because the other fields are empty & trying to parseInt & add an empty field value will result in NaN.Alternatively you can pass 0 if field is empty
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.getkeys = function(event) {
if ($scope.one === '' || $scope.two === '' || $scope.three === '' || $scope.four === "") {
$scope.one = parseInt("0");
$scope.two = parseInt("0");
$scope.three = parseInt("0")
$scope.four = parseInt("0")
}
$scope.keyval = parseInt(($scope.one) || 0, 10) + parseInt($scope.two || 0, 10) + parseInt($scope.three || 0, 10) + parseInt($scope.four || 0, 10);
console.log($scope.keyval);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<input type="text" value="22" style="width:60px;margin:6px;" ng-keyup="getkeys($event)" ng-model="one">
<input type="text" style="width:60px;margin:6px;" ng-keyup="getkeys($event)" ng-model="two">
<input type="text" style="width:60px;margin:6px;" ng-keyup="getkeys($event)" ng-model="three">
<input type="text" style="width:60px;margin:6px;" ng-keyup="getkeys($event)" ng-model="four"></div>
</div>

You don't need to bind a keyUp event, angularjs does that work for us.
Initialize the model one within the controller.
Create a function, i.e getTotal()
Use the object Number to convert the entered values to numbers.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.getTotal = function() {
return Number($scope.one) +
Number($scope.two) +
Number($scope.three) +
Number($scope.four)
};
$scope.one = 22;
$scope.two = 0;
$scope.three = 0;
$scope.four = 0;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" style="width:60px;margin:6px;" ng-model="one">
<input type="text" style="width:60px;margin:6px;" ng-model="two">
<input type="text" style="width:60px;margin:6px;" ng-model="three">
<input type="text" style="width:60px;margin:6px;" ng-model="four">
<p>Total</p>
<span>{{getTotal()}}</span>
</div>

Minior modification on #Ele code.
Change the input type from text to number to facilitate the key up event and disable characters to be entered
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.getTotal = function() {
return Number($scope.one) +
Number($scope.two) +
Number($scope.three) +
Number($scope.four)
};
$scope.one = 22;
$scope.two = 0;
$scope.three = 0;
$scope.four = 0;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="number" style="width:60px;margin:6px;" ng-model="one">
<input type="number" style="width:60px;margin:6px;" ng-model="two">
<input type="number" style="width:60px;margin:6px;" ng-model="three">
<input type="number" style="width:60px;margin:6px;" ng-model="four">
<p>Total</p>
<span>{{getTotal()}}</span>
</div>

Related

Resizing box in real time

I am trying to resize a cube whenever a new value is set in the input text-box. So far i have come across something similar, but it changes the cube only after a button is pressed.
http://jsfiddle.net/EtSf3/3/
document.getElementById('btn').addEventListener('click', function(e) {
var inputs = document.getElementsByClassName('numeric-textbox');
cube.scale.x = parseFloat(inputs[0].value) || cube.scale.x;
cube.scale.z = parseFloat(inputs[1].value) || cube.scale.z;
cube.scale.y = parseFloat(inputs[2].value) || cube.scale.y;
});
Just have to add onChange to the input fields that triggers a function to call the resize.
<input class="numeric-textbox" type="text" value="" onChange="resCube();">
function resCube() {
var inputs = document.getElementsByClassName('numeric-textbox');
cube.scale.x = parseFloat(inputs[0].value) || cube.scale.x;
cube.scale.z = parseFloat(inputs[1].value) || cube.scale.z;
cube.scale.y = parseFloat(inputs[2].value) || cube.scale.y;
}
http://jsfiddle.net/2wxbvkd3/
Change your html to this:
<script src="http://www.html5canvastutorials.com/libraries/three.min.js"></script>
<div id="container"></div>
<div class="inputRow clear" id="dimensionsNotRound" data-role="tooltip">
<label class="grid-8">Dimensions (mm):</label>
<br/>
<br/>
<div> <span>Length</span>
<input class="numeric-textbox" id='x' type="text" value="" onkeyup="updateRect(this.id, this.value)">
<br/>
<br/>
</div>
<div> <span>Width</span>
<input class="numeric-textbox" id='y' type="text" value="" onkeyup="updateRect(this.id, this.value)">
<br/>
<br/>
</div>
<div> <span>Height</span>
<input class="numeric-textbox" id='z' type="text" value="" onkeyup="updateRect(this.id, this.value)">
<br/>
<br/>
</div>
</div>
And change this function:
//Script for 3D Box
document.getElementById('btn').addEventListener('click', function(e) {
var inputs = document.getElementsByClassName('numeric-textbox');
cube.scale.x = parseFloat(inputs[0].value) || cube.scale.x;
cube.scale.z = parseFloat(inputs[1].value) || cube.scale.z;
cube.scale.y = parseFloat(inputs[2].value) || cube.scale.y;
});
to this:
const changer = {
"x": (value) => cube.scale.x = parseFloat(value) || cube.scale.x,
"y": (value) => cube.scale.y = parseFloat(value) || cube.scale.y,
"z": (value) => cube.scale.z = parseFloat(value) || cube.scale.z,
}
function updateRect(axis, value){
changer[axis](value)
}
This should change the rectangle whenever you change the input value.
You can see on this updated fiddle: http://jsfiddle.net/v5md7ug8/

How to switch min and max input values based on a condition?

I have a two input elements, where I defined min and max.
How I can reverse this values, preferably in HTML or JS (Angular).
For example:
<label>
Width:
<input type="number" min="10" max="100">
</label>
<label>
Height:
<input type="number" min="50" max="400">
</label>
If user put 400 in first input, the min and max values in second input will be replaced by min="10" max="100".
In other words, values must be interchangeable.
Here is way to do the job, using some extra variables and ng-change
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
$scope.minWidth = 10;
$scope.maxWidth = 100;
$scope.minHeight = 50;
$scope.maxHeight = 400;
$scope.update = function(v) {
if((v == 'w' && $scope.width > $scope.maxWidth) || (v == 'h' && $scope.height > $scope.maxHeight)) {
let reverseMax = $scope.maxWidth;
let reverseMin = $scope.minWidth;
$scope.maxWidth = $scope.maxHeight;
$scope.maxHeight = reverseMax;
$scope.minWidth = $scope.minHeight;
$scope.minHeight = reverseMin;
}
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<label>
Width:
<input type="number"
ng-model="width"
ng-change="update('w')"
ng-min="minWidth"
ng-max="maxWidth">
{{minWidth}} - {{maxWidth}}
</label>
<br/>
<label>
Height:
<input type="number"
ng-model="height"
ng-change="update('h')"
ng-min="minHeight"
ng-max="maxHeight">
{{minHeight}} - {{maxHeight}}
</label>
</div>

How to multiple (a*b) two input text value and show it Dynamicly with text change in javascript?

i want to show the money that customer must pay and my inputs are like this :
<input type="text" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" class="form-control" placeholder="quantity" id="txt" name="limit">
when the input text is changing i want to show the total cost (quantity*cost) in a <p> tag Dynamicly how can it be with javascript?
You can try this:
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" onchange="calculate()">
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" onchange="calculate()">
<p id="result"></p>
And javascript part:
function calculate() {
var cost = Number(document.getElementById("credit"));
var limit = Number(document.getElementById("limit"));
document.getElementById("result").innerHTML= cost*limit;
}
You must ensure you entered numbers in inputs.
All of the above will generate errors if both the boxes are blank . Try this code , its tested and running .
<script>
function calc()
{
var credit = document.getElementById("credit").value;
var limit = document.getElementById("limit").value;
if(credit == '' && limit != '')
{
document.getElementById("cost").innerHTML = parseInt(limit);
}
else if(limit == '' && credit != '')
{
document.getElementById("cost").innerHTML = parseInt(credit);
}
else if(limit!= '' && credit!= '')
{
document.getElementById("cost").innerHTML = parseInt(limit) * parseInt(credit);
}
else
{
document.getElementById("cost").innerHTML = '';
}
}
</script>
</head>
<input type="number" value="0" min="0" class="form-control" placeholder="cost" id="credit" name="credit" onkeyup="calc();">
<input type="number" value="0" min="0" class="form-control" placeholder="quantity" id="limit" name="limit" onkeyup="calc();">
<p id="cost"></p>
Hope this will be useful
// get cost field
var _cost = document.getElementById("cost");
_cost.addEventListener('keyup',function(event){
updateCost()
})
// get quantity field
var _quantity = document.getElementById("quantity");
_quantity.addEventListener('keyup',function(event){
updateCost()
})
function updateCost(){
var _getCost = document.getElementById("cost").value;
var _getQuantity = document.getElementById("quantity").value;
var _total = _getCost*_getQuantity;
console.log(_total);
document.getElementById("updateValue").textContent = ""; // Erase previous value
document.getElementById("updateValue").textContent = _total // update with new value
}
jsfiddle
In case you consider using JQuery I've made this fiddle.
See if it works for you.
https://fiddle.jshell.net/9cpbdegt/
$(document).ready(function() {
$('#credit').keyup(function() {
recalc();
});
$('#limit').keyup(function() {
recalc();
});
function recalc() {
var credit = $("#credit").val();
var limit = $("#limit").val();
var result = credit * limit;
$("#result").text(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" value="0">x
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" value="0">
<p id="result">0</p>
Try this:
<script >
function myFunction() {
document.getElementById('totalcost').innerHTML = document.getElementById('txt').value * document.getElementById('txt2').value;}
</script>
Also, change your HTML to this:
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="quantity" id="txt2" name="limit">
Enter cost and quantity.
Note the change with the second input: id='txt' was changed to id='txt2'. This is because no 2 elements can have the same id.
Note: Untested.

Changing button name depending on inputs with AngularJS

How to change button name that depends on if some inputs are empty or not
Example: if input1 and input2 is not empty but input3 is empty - button name will be "Test".
This is my code, but i doesn't work
<div ng-app="myApp">
<form action="lab2.php" method="POST" ng-controller="controller">
<label>ID</label>
<input type="number" name="id" ng-model="id" name="id"/>
{{id}}
<label>Name:</label>
<input name="name" ng-model="name" type="text"/>
<label>City:</label>
<input name="country" ng-model="country" type="text"/>
<button ng-bind="but" type="submit">{{getName()}}</button>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('controller', function($scope) {
$scope.but="Operation";
$scope.id=0;
$scope.country="";
$scope.name="";
$scope.getName = function(){
if($scope.id==0 && $scope.name!=="" && $scope.country!=="")
{
return "INSERT";
}
if($scope.id!==0 && $scope.name=="" && $scope.country=="")
{
return "DELETE";
}
if($scope.id!==0 && $scope.name!=="" && $scope.country!=="")
{
return "UPDATE";
}
}
});
</script>
var app = angular.module("app",[]);
app.controller("MyCtrl" , function($scope){
$scope.name1 = "Test";
$scope.name2 = "";
$scope.name3 = "Test3";
$scope.getName = function(){
if( $scope.name1 == "" && $scope.name2 == "" & $scope.name3 !== "")
return "Test";
return "Other";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
<input type="text" ng-model="name1">
<input type="text" ng-model="name2">
<input type="text" ng-model="name3">
<input type="button" name="{{getName()}}" value="{{getName()}}">
</div>
Try this:
<input ng-model="vm.input1" name="input1" type="text"/>
<input ng-model="vm.input2" name="input2" type="text"/>
<input ng-model="vm.input3" name="input3" type="text"/>
<button> {{(vm.input1 && vm.input2 && !vm.input3) ? 'Test' : 'Something Else' }} </button>
Something on these lines would work ...
jsfiddle: http://jsfiddle.net/0jeantca/3/
Hope this helps ...
By name do you mean the name attribute or the display text? The code below works for both.
In your template, you can write
<button name={{setName()}}>{{setName()}}</button>
and in your controller, you can write
$scope.setName = function()
{
// you can use switch here
var buttonName = "";
if($scope.input1 && $scope.input2 && !$scope.input3)
buttonName = 'Foo';
else
buttonName = 'Bar';
return buttonName;
}
Caution: As the input's change every time, the button text changes, it should be fine. But if you intend to change name attribute, then, it will cause a problem for the one who reads your code.

How to validate Save button in ng-repeat in any Index is field.?

Hello Everyone I am facing a problem regarding my save button validation. I want to validate my button if any Index is fully filled. My Save Button enable/disabled or validate properly button in case of last index. If last index is filled then the save button is working properly but in case of another index it is not working well.
Here is my Plunkr Link : http://plnkr.co/edit/IlBKTAmNBtrI79Kz8thf?p=preview
Here is my html file:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js">
</script>
<script src="script.js"></script>
</head>
<body>
<form action="#" ng-controller='detailContrller'>
<div class="control-group" ng-repeat="story in stories"> <br>
<h4> Enter data in List {{$index + 1}} </h4>
Name : <input type="text" data-ng-model="story.Name1"
placeholder="Enter Name"> <br>
Address : <input type="text" data-ng-model="story.Name2"
placeholder="Enter Address"> <br>
City : <input type="text" data-ng-model="story.Name3"
placeholder="Enter City"> <br>
Phone : <input type="text" data-ng-model="story.Name4"
placeholder="Enter Phone "> <br>
State : <input type="text" data-ng-model="story.Name5"
placeholder="Enter State"> <br>
<input type="checkbox" ng-model="story.all" ng-change="updateAll($index)">
<label class="control-label">IncludeAll</label>
<div class="controls">
<label class="checkbox inline" ng-repeat="browser in browsers">
<input type="checkbox" value="{{browser}}"
ng-model="story.browser[browser]">{{browser}}
</label>
</div>
</div>
<button type="button" data-ng-click="save()" data-ng-disabled="saveBtnDisabled" >
Save</button>
<pre>{{story | json}}</pre>
</form>
</body>
</html>
Controller
var app = angular.module("myApp",[]);
app.controller('detailContrller', function($scope){
$scope.stories = [];
$scope.browsers = ['IE', 'Chrome', 'Firefox','Safari','Opera'];
$scope.saveBtnDisabled = true;
var checked;
$scope.updateAll = function (index) {
checked = $scope.stories[index].all;
$scope.browsers.forEach(function (browser) {
$scope.stories[index].browser[browser] = checked;
});
};
for(var i = 0; i< 3; i++) {
$scope.stories.push({Name1: "", Name2: "", Name3:"", Name4: "", Name5:"", all: "",
browser:{}});
}
$scope.$watch('stories', function (newVal, oldVal) {
for(var i in newVal) {
var count = 0, keyCount = 0, selected = newVal[i];
angular.forEach(selected, function(value, p) {
if (value) {
count++;
}
keyCount ++;
})
if (count === keyCount && count >= 6) {
$scope.saveBtnDisabled = false;
} else if (count !== keyCount && count <= 6) {
$scope.saveBtnDisabled = true;
}
}
},true);
$scope.save = function () {
console.log($scope.stories);
};
});
The relevant changes to your code are inside the $scope.watch function.
Here is the JSFiddle: http://jsfiddle.net/1k1e6xxb/
HTML:
<div ng-app="myApp">
<form action="#" ng-controller='detailContrller'>
<div class="control-group" ng-repeat="story in stories"> <br>
<h4> Enter data in List {{$index + 1}} </h4>
Name : <input type="text" data-ng-model="story.Name1"
placeholder="Enter Name"> <br>
Address : <input type="text" data-ng-model="story.Name2"
placeholder="Enter Address"> <br>
City : <input type="text" data-ng-model="story.Name3"
placeholder="Enter City"> <br>
Phone : <input type="text" data-ng-model="story.Name4"
placeholder="Enter Phone "> <br>
State : <input type="text" data-ng-model="story.Name5"
placeholder="Enter State"> <br>
<input type="checkbox" ng-model="story.all" ng-change="updateAll($index)">
<label class="control-label">IncludeAll</label>
<div class="controls">
<label class="checkbox inline" ng-repeat="browser in browsers">
<input type="checkbox" value="{{browser}}" ng-model="story.browser[browser]"> {{browser}}
</label>
</div>
</div>
<button type="button" data-ng-click="save()" data-ng-disabled="saveBtnDisabled">Save</button>
<pre>{{story | json}}</pre>
</form>
</div>
JavaScript:
var app = angular.module("myApp", []);
app.controller('detailContrller', function($scope) {
$scope.stories = [];
$scope.browsers = ['IE', 'Chrome', 'Firefox', 'Safari', 'Opera'];
$scope.saveBtnDisabled = true;
var checked;
$scope.updateAll = function(index) {
checked = $scope.stories[index].all;
$scope.browsers.forEach(function(browser) {
$scope.stories[index].browser[browser] = checked;
});
};
for (var i = 0; i < 3; i++) {
$scope.stories.push({
Name1: "",
Name2: "",
Name3: "",
Name4: "",
Name5: "",
all: "",
browser: {}
});
}
$scope.$watch('stories', function(newVal, oldVal) {
var canSave = false;
angular.forEach(newVal, function (list, listNumber) {
var fieldCount = 0,
filledCount = 0;
angular.forEach(list, function (fieldValue, fieldIndex) {
if (fieldValue) {
filledCount++;
}
fieldCount++;
});
if (!canSave && fieldCount === filledCount) {
canSave = true;
}
});
if (canSave) {
$scope.saveBtnDisabled = false;
} else {
$scope.saveBtnDisabled = true;
}
},
true);
$scope.save = function() {
console.log($scope.stories);
}
});

Categories

Resources