How to toggle a checkbox when ng-repeat is used? - html

I have a problem using a switch when it is in a set of switches generated by ng-repeat. My objective is to trigger an alert when each individual checkbox is clicked.
For example, when I click the switch to enable it should alert "1", and off should alert "0", but when I click the switch to enable it alerts "1" and when i click the other switch to enable it alerts "0".
Here is a plunkr with a sample single switch
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="switchdemo">
<h1>On Off switch using Angular JS</h1>
<div ng-controller="DemoController" ng-init="init()">
<div class="well">
<label class="switch" >
<input type="checkbox" ng-model="Token" ng-change="changeStatus();">
<span class="slider round"></span>
</label>
</div>
<div class="well">
<label class="switch" >
<input type="checkbox" ng-model="Token" ng-change="changeStatus();">
<span class="slider round"></span>
</label></div>
<pre>{{ status }}</pre>
</div>
</body>
</html>
AngularJS:
angular.module('switchdemo', []).controller('DemoController', function($scope){
$scope.init = function(){
$scope.status = 1;
}
$scope.changeStatus = function(){
$scope.status = !$scope.status;
if($scope.status==1) {
$scope.status=1;
alert($scope.status);
}
else
{
$scope.status=0;
alert($scope.status);
}
}
})

In html
<div ng-controller="MyCtrl">
<input type="checkbox" ng-model="Token" ng-change="changeStatus(Token);">
</div>
in javascript and you will got true/false into alert refer link http://jsfiddle.net/ADukg/18311/
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.changeStatus = function(data){
alert(data)
};
}

Related

To show data in another div from other JSP on radio button click through ajax

I am trying to display other jsp content on radio click which is in another jsp through Ajax call.
Here is my radio button list code which is in order.jsp file
<tr>
<td>
<h2>Payment Method</h2>
<div id="demo" class="payment-method">
<ul class=list-unstyled has-border-rigth">
<li>
<input type="radio" id="creditcardpayment" name="PaymentBrands" value=" Credit Card">
<label for="creditcardpayment">Credit Card</label>
</li>
<li>
<input type="radio" id="paypalpayment" name="PaymentBrands" value=" PayPal">
<label for="paypalpayment">PayPal</label>
</li>
<li>
<input type="radio" id="purchaseorderpayment" name="PaymentBrands" value="Purchase Order">
<label for="purchaseorderpayment">Purchase Order</label>
</li>
</ul>
<div id="result"></div>
</div>
</td>
</tr>
Ajax code which is in order.jsp(same jsp) I tried three ways:
$(document).ready(function () {
$("input[type='radio']").click(function() {
var PaymentBrands = $(this).val();
alert(PaymentBrands);
$.ajax({
method:"POST",
url:"modusTest.jsp",
data: $('#result').serialize(),
dataType: "html",
success:function(response){
$('#demo').text(response);
}
});
$(document).ready(function () {
$("input[type='radio']").click(function() {
var PaymentBrands = $(this).val();
alert(PaymentBrands);
$.ajax({
url:"modusTest.jsp",
method:"POST",
data:{PaymentBrands:PaymentBrands},
success:function(data){
$('#result').html(data);
}
});
$(document).ready(function () {
var radioVal;
$("input[type='radio']").click(function() {
radioVal = $("[name=radio]:checked").val();
alert(radioVal);
$.post("/webapp/ecommerce/jsp/modusTest.jsp", {"processId": radioVal })
});
});
Below is modusTest.jsp
<html>
<head>
We are testing payment integration.
</head>
<body>
<p> Hello, how are you?</p>
</body>
</html>
Required solution as soon as possible.
This might be the solution to what you want to do.
Your main HTML file
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<tr>
<td>
<h2>Payment Method</h2>
<div id="demo" class="payment-method">
<ul class=list-unstyled has-border-rigth">
<li>
<input type="radio" id="creditcardpayment" name="PaymentBrands" value="Credit Card">
<label for="creditcardpayment">Credit Card</label>
</li>
<li>
<input type="radio" id="paypalpayment" name="PaymentBrands" value="PayPal">
<label for="paypalpayment">PayPal</label>
</li>
<li>
<input type="radio" id="purchaseorderpayment" name="PaymentBrands" value="Purchase Order">
<label for="purchaseorderpayment">Purchase Order</label>
</li>
</ul>
<div id="result"></div>
</div>
</td>
</tr>
<script>
$(document).ready(function () {
var radioVal;
$("input[type='radio']").click(function () {
//use $(this).val() instead of checked $("[name=radio]:checked").val();
//this capture accurate & instant value. for more info read more about dom update
radioVal = $(this).val();
alert(radioVal);
$.ajax({
url: "somefile.php",
method: "POST",
data: { PaymentBrands: $(this).val() },
success: function (data) {
$('#result').html(data);
}
});
});
});
</script>
Your jsp file will look the same
<html>
<head>
We are testing payment integration.
</head>
<body>
<p> Hello, how are you?</p>
</body>
</html>

Want to display error message on label in AngularJS

I want to display error message in label on click if the textbox is empty or undefined using AngularJS.
I am very beginner into AngularJS.
Please help to solve this issue.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
</head>
<body ng-app="form">
<div ng-controller="formController">
<label>Name: <input type="text" ng-model="user.name" /></label><br />
<input type="submit" ng-click="update(user)" value="Save" />
<pre>{{master | json}}</pre>
</div>
<script>
angular.module('form', []).controller('formController', ['$scope', function ($scope) {
$scope.master = {};
$scope.update = function (user) {
debugger;
$scope.master = angular.copy(user);
if (user == undefined) {
debugger;
alert("Please enter text");
}
};
}]);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<h2>Validation Example</h2>
<form ng-app="myApp" ng-controller="validateCtrl"
name="myForm" novalidate ng-submit="Validate()">
<p>Username:<br>
<input type="text" name="user" ng-model="user" required>
<span ng-show="ShowUserNameError">Username is required.</span>
</span>
</p>
</p>
<p>
<input type="submit" ng-click="Validate()">
</p>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
$scope.ShowUserNameError = false;
$scope.user = '';
$scope.email = '';
$scope.Validate = function(){
if(!$scope.user)
$scope.ShowUserNameError = true;
else
$scope.ShowUserNameError = false;
}
});
</script>
</body>
</html>
Enclose the input in a named form, name the input, and use ng-show:
<div ng-controller="formController">
<form name="form1">
<label>Name: <span ng-show="form1.item1.$error">{{form1.item1.$error}}</span>
<input name="item1" type="text" required ng-model="user.name" />
</label><br />
<input type="submit" ng-click="update(user)" value="Save" />
<pre>{{master | json}}</pre>
</form>
</div>
For more information, see
AngularJS <form> Directive API Reference - Example
AngularJS Developer Guide - Forms

Add new button after text changed

I`m using Angualr for my web.
I have this part in html code:
<div class="form-group">
<div class="text-form" style="float: left;">Companion URL</div>
<input type="text" placeholder="Companion URL" class="companion-url-box" ng-model="newCreative.companionUrl">
</div>
I want to add method (in the Controller) that when the text change, it will add a new button down.
How can I do it? I can`t understand how ng-change works.
thanks
Simply use ng-if to check if newCreative.companionUrl exists in scope :
<div class="form-group">
<div class="text-form" style="float: left;">Companion URL</div>
<input type="text" placeholder="Companion URL" class="companion-url-box" ng-model="newCreative.companionUrl">
<input type="button" value="Click me" ng-if="newCreative.companionUrl">
</div>
You can also use a function to validate button visibility :
index.html
<!doctype html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="scripts.js"></script>
</head>
<body ng-controller="SampleController as ctrl">
<div class="form-group">
<div class="text-form" style="float: left;">Companion URL</div>
<input type="text" placeholder="Companion URL" class="companion-url-box" ng-model="newCreative.companionUrl">
<input type="button" value="Click me" ng-if="ctrl.isButtonAvailable()">
</div>
</body>
</html>
script.js
angular.module('app', []);
angular.module('app').controller('SampleController', function ($scope) {
var ctrl = this;
ctrl.isButtonAvailable = function() {
if(!$scope.newCreative) {
return false;
}
// Ensure companion url starts with https:// using a regular expression
return /^https:\/\//.test($scope.newCreative.companionUrl);
}
});
Working example
Check out this Plunker : https://plnkr.co/edit/n8VtJrenePGf9hCbmzWJ
You can use the directives ng-change on input and ng-if or ng-show on button, plus a little code on controller.
Check this:
http://codepen.io/mQuixaba/pen/oZqXWG?editors=1111
HTML:
<div ng-app="myApp" ng-controller="MyController">
<label for="input">Text:</label>
<input type="text" id="input" ng-model="text" ng-change="showButton=true"/>
<button ng-if="showButton" ng-click="hideButton()">My Button</button>
</div>
JS:
angular
.module('myApp', [])
.controller('MyController', function($scope){
$scope.showButton = false;
$scope.text = "My text";
$scope.hideButton = function() {
$scope.showButton = false;
}
});

Focus back to textbox on blur event angular

View:
<label class="item item-input">
<input type="text" ng-model="scan.text" placeholder="Scan here" ng-enter="scanBarcode2(scan)" ng-focus="hideKey()">
<span>{{scantext.text}}</span>
</label>
Controller
.controller('RollCallScan2Ctrl', function($scope,$stateParams, Api, $cordovaBarcodeScanner,$filter,$ionicPopup) {
var a=[], b={};
$scope.empdata = a;
$scope.scan = {text: ""};
})
I want to set focus on textbox, when view is loaded and whenever focus is off from it or user touches anywhere in screen. I need to focus back to textbox.
You can do this by using 'ng-blur' directive in Angular. I have created a sample plnkr with setTimeout to see the focus which is going back to textbox when the focus is out
http://plnkr.co/edit/JNfYmL0Bk7pcJXQdQWWN?p=preview
JS:
angular.module("focusApp", [])
.controller("focusController", function($scope) {
document.getElementById('sampleText').focus();
$scope.focusTextBox = function() {
setTimeout(function() {
document.getElementById('sampleText').focus();
}, 100);
};
});
HTML:
<html ng-app="focusApp">
<head>
<script data-require="angular.js#1.5.8" data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="focusController">
<input type="text" id="sampleText" placeholder="Focussed text box" ng-blur="focusTextBox()"><br /><br />
<input type="text" placeholder="Text box to test Focus">
</body>
</html>

knockout does not change the radio button view

I have a working panel with radio buttons a label and a textfield. Everything works good except if i click on radio buttons explicitly the radio button does not change the radio button view.
Here the plnkr link to it:
https://embed.plnkr.co/auD0sMEL88EsuaQqvt7E/
As #user3297291 mention that the checked and click binding get in confict.
Add this binding:
ko.bindingHandlers.stopBubble = {
init: function(element) {
ko.utils.registerEventHandler(element, "click", function(event) {
event.cancelBubble = true;
if (event.stopPropagation) {
event.stopPropagation();
}
});
}
};
You have to add in every radio element this binding like this:
<input data-bind="checked: discountValue, stopBubble: true" id="discountArbitrary" name="discount" type="radio" value="arbitrary" />
I created one jsfiddle that works as you expected.
https://jsfiddle.net/astrapi69/s3r60uLu/
I guess the click binding is conflicting with checked binding.
You can use computeds to calculate enabled/focused flags.
You can check modified code (I've omitted focused flags in favor of simplicity):
// Code goes here
var DiscountViewModel = function() {
var self = this;
self.arbitrary = ko.observable();
self.percent = ko.observable();
self.permanent = ko.observable();
self.discountValue = ko.observable('arbitrary');
self.enableArbitrary = ko.computed(() => self.discountValue() === 'arbitrary');
self.enablePercent = ko.computed(() => self.discountValue() === 'percent');
self.enablePermanent = ko.computed(() => self.discountValue() === 'permanent');
self.onArbitrary = onArbitrary;
self.onPercent = onPercent;
self.onPermanent = onPermanent;
function onArbitrary() {
self.discountValue('arbitrary');
}
function onPercent() {
self.discountValue('percent');
}
function onPermanent() {
self.discountValue('permanent');
}
};
var vm = new DiscountViewModel();
ko.applyBindings(vm);
/* Styles go here */
.header-line {
margin-bottom:20px;
margin-top:20px;
margin-left:20px;
}
<script data-require="jquery#2.1.3" data-semver="2.1.3" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.3.3/js/tether.js"></script>
<link data-require="bootstrap#4.0.0-alpha.2" data-semver="4.0.0-alpha.2" rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/css/bootstrap.css" />
<script data-require="bootstrap#4.0.0-alpha.2" data-semver="4.0.0-alpha.2" src="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/js/bootstrap.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-debug.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js" type="text/javascript" defer="defer"></script>
<h1 class="header-line">
KO binding hasFocus over boolean values
</h1>
<div class="form-group row">
<div class="col-xs-1">
</div>
<div class="col-xs-1">
<input name="discount" type="radio" value="arbitrary" data-bind="checked: discountValue" />
</div>
<div class="col-xs-4">
<label for="arbitrary" data-bind="click: onArbitrary">Discount arbitrary</label>
</div>
<div class="col-xs-5">
<input type="text" class="form-control" id="arbitrary" placeholder="Enter arbitrary discount" data-bind="enable: enableArbitrary, value: arbitrary, hasFocus: enableArbitrary">
</div>
</div>
<div class="form-group row">
<div class="col-xs-1">
</div>
<div class="col-xs-1">
<input name="discount" type="radio" value="percent" data-bind="checked: discountValue" />
</div>
<div class="col-xs-4">
<label for="percent" data-bind="click: onPercent">Discount percent</label>
</div>
<div class="col-xs-5">
<input type="text" class="form-control" id="percent" placeholder="Enter percent of discount" data-bind="enable: enablePercent, value: percent, hasFocus: enablePercent">
</div>
</div>
<div class="form-group row">
<div class="col-xs-1">
</div>
<div class="col-xs-1">
<input name="discount" type="radio" value="permanent" data-bind="checked: discountValue" />
</div>
<div class="col-xs-4">
<label for="permanent" data-bind="click: onPermanent">Discount permanent</label>
</div>
<div class="col-xs-5">
<input type="text" class="form-control" id="permanent" placeholder="Enter permanent discount" data-bind="enable: enablePermanent, value: permanent, hasFocus: enablePermanent">
</div>
</div>
The problem is that by clicking the radio button, two things happen:
The checked binding does its thing
The event bubbles up to the parent element, and the click binding also does its thing.
You'll have to make sure clicking the input element stops the click binding from firing.
There's a great answer by R.P. Niemeyer here: https://stackoverflow.com/a/14321399/3297291