get string to ng-model value angular js - javascript

I have 10 input fields each of them looks like:
<input type='text' ng-model='value1' ng-keyup='checkValue($event)'>
now inside my angular controller, the checkValue function is
$scope.checkValue = function(event){
if(event.target.value > someOtherDynamicValue){
// I have to reset the value here
event.target.value = "";
}
}
here the value is getting empty if the if condition is true but the problem is this value is not removing from ng-model. So I tried to access the ng-model name of the target element like this:
var modelName = angular.element(event.target)[0]attributes[2].nodeValue;
So now in modelName i have the ng-model name of the target element and I tried to reset it :
$scope.modelName = "";
So finally my code looks like:
$scope.checkValue = function(event){
if(event.target.value > someOtherDynamicValue){
// I have to reset the value here
event.target.value = "";
var modelName = angular.element(event.target)[0]attributes[2].nodeValue;
$scope.modelName = "";
}
}
I know it is treating $scope.modelName as a new independent scope variable but how can I change the value of ng-model?
EDIT
What I really want to achieve is: I have 10 fields with different ng-model name now when I am writing the angular function, I don't want to use the ng-model directly inside the function. Example:
$scope.checkValue = function(event){
if(event.target.value > someOtherDynamicValue){
// I have to reset the value here
$scope.value1 = ""; //I don't want to do this, because $scope.value1 is for one text field and I have 10 filed if i use this i need to write it 10 times
}
}
So $scope.value1 I want to generate dynamically using event.target.
Thanks.

Based on values you enter on third textbox values of one and two changes
// Code goes here
var app = angular.module('TestApp', []).controller('HomeController', HomeController);
HomeController.$inject = ['$scope'];
function HomeController($scope) {
var home = this;
home.checkValue = function($event) {
if ($event.target.value < 100) {
home.val1 = 0;
}else{
home.val2 = 10;
}
}
}
<!DOCTYPE html>
<html ng-app="TestApp">
<head>
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="HomeController as home">
<div>
{{ home.val1 }} | {{ home.val2 }} | {{ home.val3}}
</div>
<input type="number" ng-model="home.val1" ng-keyup='home.checkValue($event)'>
<input type="number" ng-model="home.val2" ng-keyup='home.checkValue($event)'>
<input type="number" ng-model="home.val3" ng-keyup='home.checkValue($event)'>
</div>
</body>
</html>

Related

Update a JS array value with a global variable based on checkbox (true/false) form input

I'm using a WorldPay JS function to create a payment form. This function creates a TOKEN that can be reusable or not. I need to update the 'reusable' flag based on a form input (checkbox) but I can't get the global variable (reuse) to update. I've created a function CHECKED that updates the variable but the WorldPay JS just ignores it. I think is due the window.onload status, but I don't know how to fix it. Any help would be greatly appreciated.
<?php
include('./header.php');
require_once('./init.php');
?>
<html>
<head>
<title></title>
<meta charset="UTF-8" />
<script src="https://cdn.worldpay.com/v1/worldpay.js"></script>
<script type='text/javascript'>
var reuse = false;
function Checked(){
reuse = document.getElementById('check').checked;
Worldpay.submitTemplateForm();
}
window.onload = function() {
Worldpay.useTemplateForm({
'clientKey':'ENTER CLIENT KEY',
'form':'paymentForm',
'paymentSection':'paymentSection',
'display':'inline',
'type':'card',
'reusable': reuse,
'saveButton':false,
'callback':function(obj){
if (obj && obj.token && obj.paymentMethod) {
var _el = document.createElement('input');
_el.value = obj.token;
_el.type = 'hidden';
_el.name = 'token';
document.getElementById('paymentForm').appendChild(_el);
var _name = document.createElement('input');
_name.value = obj.paymentMethod.name;
_name.type = 'hidden';
_name.name = 'customer';
document.getElementById('paymentForm').appendChild(_name);
document.getElementById('paymentForm').submit();
}
}
});
}
</script>
</head>
<body>
<form action="./test.php" id="paymentForm" method="post">
<!-- all other fields you want to collect, e.g. name and shipping address -->
<div id='paymentSection'></div>
<div>
<input type="checkbox" id='check'>
<input type="submit" value="Place Order" onclick="Checked()" />
</div>
</form>
</body>
</html>
NOTE: I've removed the client ID so the code won't run.
Have you tried to use function "checked" on window.onload like this:
window.onload = function() {
Worldpay.useTemplateForm({
//code....
)}
function Checked(){
//code....
}

Concatenate (append) one input field value to another field in angular form

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?

Add items to a shopping cart in AngularJS

Angular beginner here.
I'm trying to create a shopping cart for college.
I need to add the name and price in a text input and after clicking a button the item is supposed to be added to a list.
The thing is that whenever I press the button nothing happens, and I'm lost since the console doesn't tell me anything about what could be wrong. So, here's my code:
<!DOCTYPE html>
<html ng-app = "myApp">
<head>
<title>Shopping Cart</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
<script src = "app.js"></script>
</head>
<body ng-controller = "myShoppingCart">
<h1>Add to cart</h1>
<form >
<p>Product: <input type = "text" ng-model = "nameProduct"></p>
<p>Price: <input type = "number" min = "0" step = "any" ng-model = "priceProduct"></p>
<input type = "submit" value = "Add" ng-click = "addProduct()">
</form>
</div>
<div">
<ul>
<li ng-repeat = "product in products">
<span>{{product.name}}</span>
<span>{{product.price}}</span>
<span><input type = "number" min = "0" placeholder = "0" value = "0" ng-model = "amount"></span>
<span>{{product.price*amount}}</span>
</li>
</ul>
</div>
</body>
</html>
And this is my js code:
var myApp = angular.module("myApp", []);
myApp.controller('myShoppingCart', function($scope) {
$scope.products = [];
function addProduct() {
$scope.productos.push({nombre:$scope.nameProduct, price:$scope.priceProduct});
$scope.nameProduct = "";
$scope.priceProduct = "";
}
});
You have pushed the values to wrong object .
and also you need to change lot .and your button click should be need write to
$scope.addProduct= function () {
//code
}
So please copy and past my code to instead of your code
HTML
<!DOCTYPE html>
<html ng-app = "myApp">
<head>
<title>Shopping Cart</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
<script src = "app.js"></script>
</head>
<body ng-controller = "myShoppingCart">
<h1>Add to cart</h1>
<form >
<p>Product: <input type = "text" ng-model = "nameProduct"></p>
<p>Price: <input type = "number" min = "0" step = "any" ng-model = "priceProduct"></p>
<input type = "submit" value = "Add" ng-click = "addProduct()">
</form>
</div>
<div>
<ul>
<li ng-repeat = "product in products">
<span>{{product.name}}</span>
<span>{{product.price}}</span>
<span><input type = "number" min = "0" placeholder = "0" value = "0" ng-model = "amount"></span>
<span>{{product.price*amount}}</span>
</li>
</ul>
</div>
</body>
</html>
and JS Code
var myApp = angular.module("myApp", []);
myApp.controller('myShoppingCart', function($scope) {
$scope.products = [];
$scope.addProduct= function () {
$scope.products.push({name:$scope.name, price:$scope.priceProduct});
$scope.nameProduct = "";
$scope.priceProduct = "";
}
});
<input type = "submit" value = "Add" ng-click = "addProduct()">
Needs to be
<input type = "button" value = "Add" ng-click = "addProduct()">
Submit will submit the form to the server, not exactly what you're looking for I guess.
Also, bad typo here:
<div">
And here (products, not productos):
$scope.productos

Calculate form inputs onChange

I have a dynamic form that is being generated based on what the user adds to the cart.
For example, the form will looks something like this,
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test Form</title>
</head>
<body>
<form action="" name="cart" id="cart">
<input type="text" name="sku1">
<input type="text" name="sku2">
<input type="text" name="sku3">
<input type="text" name="sku4">
<input type="text" name="sku5">
<div class="sum" id="sum"> Total: {SUM SHOULD SHOW UP HERE)</div>
<button name="submit">Send</button>
</form>
</body>
</html>
But those input fields are generated automatically and may be more or less than 5 fields.
How to calculate those input SUM value and output to SUM div without page refresh?
JavaScript/jQuery?
$('button[name="submit"]').click(function () {
var sum = 0;
$('#cart input[name^="sku"]').each(function () {
var val = isNaN(+this.value) ? 0 : +this.value;
sum += val;
});
$('#sum').text(sum);
});
Or
var inp = $('#cart input[name^="sku"]');
inp.change(function () {
var sum = 0;
inp.each(function () {
var val = isNaN(+this.value) ? 0 : +this.value;
sum += val;
});
$('#sum').text(sum);
});
Attribute Starts With Selector [name^="value"]
.change()
isNaN()
You can use the onsubmit attribute of the form to do whatever you want to before the form gets submitted. You can change action attribute also. You can also preventDefault as said here-
jQuery on submit preventDefault() does not works
You can give the elements a class, amountForTotal, and use a function to calc the total, which you can add to a button, or onchange event of an input.
function calcTotal( $elements ){
var total = 0;
$elements.each(function(){
// if the input has no value, add 0, if it has, add the value
total+= this.value.length===0 ? 0 : parseInt(this.value);
})
return total; // return the total
}
$elements = $('.amountForTotal'); // select them
// Bind an event to recalc the total
$elements.on('keyup', function(){
alert( calcTotal($elements) );
});
In this code I provided the selector as input. This is luxery, not needed, you can add that selector in the function, but this way it can be used more flexible. You can use the [name^=*] selector here, but its slower than a class, which you might notice in large documents.
Also, In my code I check if it has to no value to prevent errors. You can expand this to test if the input is actualy a number.

copy text from one textbox to another based on a condition

I am working on javascript.
Consider two textboxes tb1 and tb2 respectively
The value present in tb1 should be copied in tb2 based on a condition. If the condition is true nothing needs to be copied. If the condition is false the value in tb1 should also be initialised to tb2. Is it possible..
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div>
<span>tb1:</span>
<input id="tb1" type="text" value="TextBox Value 1"/>
</div>
<div>
<span>tb2:</span>
<input id="tb2" type="text" value="TextBox Value 2"/>
</div>
<input type="button" onclick="exchange()" value="Exchange">
<script type="text/javascript">
function exchange(){
var tb1 = document.getElementById('tb1');
var tb2 = document.getElementById('tb2');
var condition = function(){
return true;
};
if(condition()){
var buf = tb1.value;
tb1.value = tb2.value;
tb2.value = buf;
}
}
</script>
</body>
</html>
Here's a function that can do what you need:
function compareAndCopy() {
var tb1 = document.getElementById("tb1");
var tb2 = document.getElementById("tb2");
if (tb1.value == "hey") {
tb2.value = tb1.value;
} else {
alert("No match");
}
}
//Add a handler
document.getElementById("tb1").onblur = compareAndCopy;
It is currently checking if tb1 equals hey on blur.
Working demo: http://jsfiddle.net/4L5pE/
yes, this is possible. You need to define when you want it to happen. onkeypress, or onblur of first text box you can call a function that validates your condition and then copies the values.
tb1.onblur(function(){ if(condition) tb2.value = tb1.value }
the code above will not work, its just a pseudo.

Categories

Resources