Check/Uncheck boxes when another is clicked in javascript - checkbox

Trying to clear 2 check boxes when another is clicked. I've searched for this answer and have tried using information from the examples but for some reason nothing I try works. Here is the code I am currently using.
function control()
{
/*var one = document.getElementById('one');
var two = document.getElementById('two');
var three = document.getElementById('three');*/
if(document.forms[0].one.checked == true)
{
document.forms[0].two.checked == false;
document.forms[0].three.checked == false;
}
if(document.forms[0].two.checked == true)
{
document.forms[0].three.checked == false;
document.forms[0].one.checked == false;
}
if(document.forms[0].three.checked == true)
{
document.forms[0].one.checked == false;
docuemnt.forms[0].two.checked == false;
}
}
</SCRIPT>
</head>
<body>
<form action="" method="POST" name="getArea">
<input type="checkbox" onClick="control()" name="one">Standard Shipping<br />
<input type="checkbox" onClick="control()" name="two">Overnight Shipping<br />
<input type="checkbox" onClick="control()" name="three">Priority Shipping<br />
</form>
</body>
</html>

Are you trying something like below?
<html>
<head>
<script type="text/javascript">
function control(idSelected)
{
/*var one = document.getElementById('one');
var two = document.getElementById('two');
var three = document.getElementById('three');*/
if(idSelected==1)
{
document.forms[0].two.checked = false;
document.forms[0].three.checked = false;
}
if(idSelected==2)
{
document.forms[0].three.checked = false;
document.forms[0].one.checked = false;
}
if(idSelected==3)
{
document.forms[0].one.checked = false;
docuemnt.forms[0].two.checked = false;
}
}
</SCRIPT>
</head>
<body>
<form action="" method="POST" name="getArea">
<input type="checkbox" onClick="control(1)" name="one">Standard Shipping<br />
<input type="checkbox" onClick="control(2)" name="two">Overnight Shipping<br />
<input type="checkbox" onClick="control(3)" name="three">Priority Shipping<br />
</form>
</body>
</html>

Related

Calculator built using AngularJS not showing result

In AngularJs Tutorial I have built a simple Calculator but when I click on calculate button it does not show the output. I am not sure where I am doing the mistake. The HTML file has three text input fields and five buttons. When I click on calculate button the output doesn't appear
My HTML file code
<!DOCTYPE html>
<html data-ng-app="calc">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div align="center" data-ng-controller="CalcCtrl as c1">
<input type="text" data-ng-model="c1.num1"></input>
<span data-ng-bind="c1.selectedOperation"></span>
<input type="text" data-ng-model="c1.num2"></input>
<span></span>
<input type="text">{{c1.result}}</input>
<p>
<button data-ng-click="c1.buttonClicked('+')">+</button>
<button data-ng-click="c1.buttonClicked('-')">-</button>
<button data-ng-click="c1.buttonClicked('*')">*</button>
<button data-ng-click="c1.buttonClicked('/')">/</button>
</p>
<p>
<button data-ng-click="c1.calcResult()">calculate</button>
</p>
{{c1.num1}} {{c1.num2}}
</div>
</body>
</html>
My App.JS file
var app = angular.module("calc", []);
app.controller('CalcCtrl', calc);
function calc() {
this.result = 0;
this.buttonClicked = function(button){
this.selectedOperation=button;
}
this.calcResult=function(){
var1 n1=parseFloat(this.num1);
var2 n2=parseFloat(this.num2);
if(this.selectedOperation==='+') {
this.result = n1+n2;
}else if(this.selectedOperation==='-') {
this.result = n1-n2;
}else if(this.selectedOperation==='*') {
this.result = n1*n2;
}else if(this.selectedOperation==='\') {
this.result = n1/n2;
}
}
}
I don't know what are the changes I did from your code, because I have changed more code and added some features. You can just copy paste this below snippet.
Working Snippet
angular.module("calc",[]).controller('CalcCtrl', function($scope) {
$scope.result = 0;
$scope.buttonClicked = function(button){
this.selectedOperation=button;
};
$scope.calcResult = function(){
var n1 = parseFloat($scope.num1);
var n2 = parseFloat($scope.num2);
if($scope.selectedOperation==='+') {
$scope.result = n1+n2;
}else if($scope.selectedOperation==='-') {
$scope.result = n1-n2;
}else if($scope.selectedOperation==='*') {
$scope.result = n1*n2;
}else if($scope.selectedOperation==='/') {
$scope.result = n1/n2;
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="calc" align="center" ng-controller="CalcCtrl">
<input type="text" ng-change="calcResult()" ng-model="num1"></input>
<span ng-bind="selectedOperation"></span>
<input type="text" ng-change="calcResult()" ng-model="num2"></input>
<span></span>
<input type="text" ng-model="result"></input>
<p>
<button ng-click="buttonClicked('+');calcResult()">+</button>
<button ng-click="buttonClicked('-');calcResult()">-</button>
<button ng-click="buttonClicked('*');calcResult()">*</button>
<button ng-click="buttonClicked('/');calcResult()">/</button>
</p>
<p>
<button ng-click="calcResult()">calculate</button>
</p>
{{num1}}{{selectedOperation}} {{num2}} = {{result}}
</div>
else if(this.selectedOperation==='\') must be else if(this.selectedOperation==='/'). You are escaping the second quotation mark.
At first the input tag is a standalone tag and has no value inside. Try to use data-ng-model instead or set the value to a span.
<input type="text" data-ng-model="c1.result" />
or
<span>{{c1.result}}</span>
Then have a look at the browser console if there are any errors reported.

Using Angular, how to display validation issues on an event?

I do not want to render validation issues until a user attempts to submit my form.
I have a form with 2 fields, one is required and ng-minlength=5, the other is ng-minlength=5. If the fields are invalid, I would like to display them with a red background if the user attempts to submit the form.
I am attempting to do this by determining the style in the controller based on the field's validity and if the submit button has been clicked.
This isn't working for me though, the field never displays as red. Any suggestions as to how I can get this approach to work?
Is this a reasonable approach, or is there a strategy more idiomatic to Angular?
https://jsfiddle.net/dk89dhp2/
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>
<style>
.my_invalid{
border-color:#ffdddd;
background-color:#ffdddd;
background-image: none;
}
</style>
<body ng-app="myapp">
<div ng-controller="MyController" >
<form name="myFormNg">
<input type="text" class="myForm.getFormFieldCssClass(myFormNg.id)" name="id" ng-model="myForm.id" ng-minlength="5" required> Id <br/>
<input type="text" class="myForm.getFormFieldCssClass(myFormNg.name)" name="name" ng-model="myForm.name" ng-minlength="5"> Name <br/>
<button type="button" ng-click="myForm.submit()">Submit</button>
</form>
<script>
angular.module("myapp", [])
.controller("MyController", function($scope) {
$scope.myForm = {};
$scope.showErrors = false;
$scope.myForm.submit = function() {
$scope.showErrors = true;
}
$scope.myForm.getFormFieldCssClass = function(ngModelController) {
if (ngModelController.$pristine)
return "";
return ngModelController.$valid && $scope.showErrors ? "" : "my_invalid";
// additional logic to check if empty and required?
}
} );
</script>
now it's not working because you're using class that allow you to bind only "static" classes instead of the ng-class directive.
i'd change your code just to add the directive, about your approach, i'd stick with it, you need some sort of control that check if the form is valid and if the error are enabled.
<input type="text" ng-class="{'input1Error': myForm.getFormFieldCssClass(myFormNg.id})" />
<input type="text" ng-class="{'input2Error': myForm.getFormFieldCssClass(myFormNg.id})" />
then at the end of your method change the return type to boolean to determine whether to apply or not the class
$scope.myForm.getFormFieldCssClass = function(ngModelController) {
if (ngModelController.$pristine)
return false;
return ngModelController.$invalid && $scope.showErrors ? true : false;
}
you can try as below also.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>
<style>
.my_invalid{
border-color:#ffdddd;
background-color:#ffdddd;
background-image: none;
}
</style>
<body ng-app="myapp">
<div ng-controller="MyController" >
<form name="myFormNg">
<input type="text" class="myForm.getFormFieldCssClass(myFormNg.id)" id="textbox1" name="id" ng-model="myForm.id" ng-minlength="5" required> Id <br/>
<input type="text" class="myForm.getFormFieldCssClass(myFormNg.name)" id="textbox2" name="name" ng-model="myForm.name" ng-minlength="5"> Name <br/>
<button type="button" ng-click="myForm.submit()">Submit</button>
</form>
<script>
angular.module("myapp", [])
.controller("MyController", function($scope) {
$scope.myForm = {};
$scope.showErrors = false;
$scope.myForm.submit = function() {
angular.element('#textbox1').css('border-color', 'red');
angular.element('#textbox2').css('border-color', 'red');
}
$scope.myForm.getFormFieldCssClass = function(ngModelController) {
if (ngModelController.$pristine)
return "";
return ngModelController.$valid && $scope.showErrors ? "" : "my_invalid";
// additional logic to check if empty and required?
}
} );
</script>
</body>
</html>

disable button is not working while using ng-disabled

Initially the value of button is disable because value of button is true so the button is disabled.After selecting the checkbox now the button should be able to click. But it is not able to click :
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="checkbox" ng-model="formData.week[0]" ng-true-value="'a'">a
<input type="checkbox" ng-model="formData.week[1]" ng-true-value="'s'">s
<input type="checkbox" ng-model="formData.week[2]" ng-true-value="'d'">d
<input type="checkbox" ng-model="formData.week[3]" ng-true-value="'f'">f
<input type="checkbox" ng-model="formData.week[4]" ng-true-value="'g'">g
<input type="submit" ng-disabled='!formData.week.length' ng-click=a(formData)>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.a = function(x) {
console.log(x);
a = [1, 2, 3];
console.log(a);
}
});
</script>
</body>
</html>
Your ng-disabled always checks for length. But you actually need to check the boolean value of your checkbox to satisfy the scenario you are trying to achieve.
I have updated your code to the code below
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="checkbox" ng-model="formData.week[0]" ng-true-value="'a'">a
<input type="checkbox" ng-model="formData.week[1]" ng-true-value="'s'">s
<input type="checkbox" ng-model="formData.week[2]" ng-true-value="'d'">d
<input type="checkbox" ng-model="formData.week[3]" ng-true-value="'f'">f
<input type="checkbox" ng-model="formData.week[4]" ng-true-value="'g'">g
<input type="submit" ng-disabled='formData.week[0]==false &&
formData.week[1]==false &&
formData.week[2]==false &&
formData.week[3]==false &&
formData.week[4]==false
' ng-click=a(formData)>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.formData = {}
$scope.formData.week = []
$scope.formData.week[0]=false;
$scope.formData.week[1]=false;
$scope.formData.week[2]=false;
$scope.formData.week[3]=false;
$scope.formData.week[4]=false;
});
</script>
</body>
</html>
change ng-disabled='!formData.week.length'
to
ng-disabled='!(!!formData.week[0] || !!formData.week[1] || !!formData.week[2] || !!formData.week[3] || !!formData.week[4])'
check out the working example : https://plnkr.co/edit/JOARO1NwgunCw5Zcyvpo?p=preview
Actually there is something to understand
<div ng-app="myApp" ng-controller="myCtrl">
<input type="checkbox" ng-model="formData.week[0]" ng-true-value="'a'">a
<input type="checkbox" ng-model="formData.week[1]" ng-true-value="'s'">s
<input type="checkbox" ng-model="formData.week[2]" ng-true-value="'d'">d
<input type="checkbox" ng-model="formData.week[3]" ng-true-value="'f'">f
<input type="checkbox" ng-model="formData.week[4]" ng-true-value="'g'">g
<input type="submit" ng-disabled='!formData.week.length' ng-click=a(formData)>
</div>
So when you are applied NgModel as formData.week[0] so it will form the scope variable formData something like that
{
"week" :{"0":true,"1" : true", "2" : "false"
}
as you have not declared formData.week as an array. So for this object to be checked on length you need to make a function like
<input type="submit" ng-disabled='!checkLength()' ng-click=a(formData)>
the function will look like
$scope.checkLength = function(){
if($scope.formData && $scope.formData.week && Object.keys($scope.formData.week).length > 0)
return true;
else
return false;
}
Moreover if you want the button enabled only when any of the checkboxes is true. then you may modify the function
$scope.checkLength = function(){
if($scope.formData && $scope.formData.week && Object.keys($scope.formData.week).length > 0) {
var point = 0;
for(var i=0;i< Object.keys($scope.formData.week).length;i++){
if($scope.formData.week[i] == true){
point++;
break;
}
}
if(point>0) return true;
else return false;
}
else
return false;
}

Treat check-boxes like radio buttons in AngularJS

Problem: we have a group of check-boxes.i want only one checked at a time(like as radio button).
I am doing like this.
In View
<div>
<input type="checkbox" ng-model="first" ng-change="checkOne('1')" />
<div ng-if="first">
<label>Hi</label>
</div>
<input type="checkbox" ng-model="second" ng-change="checkOne('2')" />
<div ng-if="second">
<label>Adem</label>
</div>
</div>
In Controller
function controller(){
$scope.checkOne=function(val){
if(val == '1'){
$scope.first=true;
$scope.second=false;
}
if(val == '2'){
$scope.second=true;
$scope.first=false;
}
}
}
But it is not working.it selects both the check-boxes.
Please suggest me a solution.
Thanks.
Try this:
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"> </script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="controller">
<input type="checkbox" ng-model="first" ng-change="checkOne('1')" />
<div ng-if="first">
<label>Hi</label>
</div>
<input type="checkbox" ng-model="second" ng-change="checkOne('2')" />
<div ng-if="second">
<label>Adem</label>
</div>
</div>
</body>
</html>
script.js
function controller($scope) {
$scope.checkOne=function(val){
if(val == '1'){
$scope.first=true;
$scope.second=false;
}
if(val == '2'){
$scope.second=true;
$scope.first=false;
}
}
}
http://plnkr.co/edit/WEn4CBXA3RvtZ33VuPyM?p=preview
You need to use ng-checked.
I also set any checked checkboxes to be disabled so that they can't be unchecked.
After that, a simple function with a switch statement to toggle all of them on ng-click.
Controller:
$scope.firstCheck = true;
$scope.checkToggle = function(checkbox) {
switch (checkbox) {
case 'first':
$scope.firstCheck = true;
$scope.secondCheck = false;
$scope.thirdCheck = false;
break;
case 'second':
$scope.firstCheck = false;
$scope.secondCheck = true;
$scope.thirdCheck = false;
break;
case 'third':
$scope.firstCheck = false;
$scope.secondCheck = false;
$scope.thirdCheck = true;
break;
}
}
HTML:
<div>
<input type="checkbox" ng-disabled="firstCheck" ng-click="checkToggle('first')" ng-model="first" ng-checked="firstCheck" />
<div ng-if="first">
<label>Hi</label>
</div>
<br/><input type="checkbox" ng-disabled="secondCheck" ng-click="checkToggle('second')" ng-model="second" ng-checked="secondCheck" />
<div ng-if="second">
<label>Adem</label>
</div>
<br/><input type="checkbox" ng-disabled="thirdCheck" ng-click="checkToggle('third')" ng-model="third" ng-checked="thirdCheck" />
<div ng-if="third">
<label>something else</label>
</div>
Checkbox Treat as RadioButton : Here We have four checkbox, and all should be work as RadioButton. Checkbox with ng-change is use for change value of ng-model.
http://plnkr.co/edit/yTJUZcFoLsSEBjruRuEY?p=preview
App.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.first = false;
$scope.second = false;
$scope.third = false;
$scope.fourth = false;
});
HTML
<div>{{first}}|{{second}}|{{third}}|{{fourth}}
<br/>
<input type="checkbox" ng-model="first" ng-change="second=false;third = false;fourth = false;" />
<input type="checkbox" ng-model="second" ng-change="first = false;third = false;fourth = false;" />
<input type="checkbox" ng-model="third" ng-change="first =false;second = false;fourth = false;" />
<input type="checkbox" ng-model="fourth" ng-change="first = false;second = false;third = false;" />
</div>

Cleaning up validation logic

I've just got validation working the way I want with the following code:
<div class="control-group" ng-class="{ error : (submitted || accountForm.name.$dirty) && accountForm.name.$invalid }">
<label for="name" class="control-label">Company Name:</label>
<input type="text" name="name" ng-model="account.name" ng-maxlength="50" required />
<span class="help-inline" ng-show="(submitted || accountForm.name.$dirty) && accountForm.name.$error.maxlength">Name too long</span>
<span class="help-inline" ng-show="(submitted || accountForm.name.$dirty) && accountForm.name.$error.required">Required</span>
</div>
But there seems to be a lot of similar code with only slight differences. What would be the best method of simplifying this to make it a) clearer, b) more maintainable?
Update 23/07 Doesn't seem like there's an immediate best practice.
You could make an error variable in the $scope of the controller that controls that template. Something like this:
html
<div ng-controller="FormCtrl" class="control-group" ng-class="{ error : (submitted || accountForm.name.$dirty) && accountForm.name.$invalid }">
<label for="name" class="control-label">Company Name:</label>
<input type="text" name="name" ng-model="account.name" ng-maxlength="50" required />
<input type="button" ng-click="submitForm()" />
<span class="help-inline">{{ error }}</span>
</div>
controller
window.FormCtrl = function ($scope) {
$scope.error = "";
$scope.submitForm = function() {
if ($scope.accountForm.name.length > 50) {
$scope.error = "Name too long";
}
else if ($scope.accountForm.name == null || $scope.accountForm.name == undefined) {
$scope.error = "Name required";
}
else {
$scope.error = "";
//submit logic
}
}
}
Since you want to reuse the same code for other form fields, and the validation logic seems to be similar for each of them, i could not find anything with ngForm that would help reuse the code. Rather I would suggest a different approach, where you don't use ngForm and do the validation in js yourself. This way you can reuse the method everywhere.
Here is the link for the jsFiddle:
http://jsfiddle.net/rCDg8/1/
<div ng-app>
<div ng-controller="DemoCtrl">
<form name="accountForm" ng-submit="submit()">
<div class="control-group" ng-class="class">
<label for="name" class="control-label">Company Name:</label>
<input type="text" name="name" ng-model="account.name" ng-change="validateEntry(account.name)" required></input>
<span class="help-inline" ng-show="accountForm.$dirty||accountForm.$invalid">{{msg}}</span>
</div>
</form>
</div>
</div>
Controller:
function DemoCtrl($scope) {
var longName = 'Name too long';
var nameRequired = 'Name is required!';
$scope.class = '';
$scope.showMsg = false;
$scope.validateEntry = function (validateItem) {
if (angular.isDefined(validateItem)) {
if (validateItem.length > 50) {
showErrorMsg(longName);
} else if (validateItem.length === 0) {
showErrorMsg(nameRequired);
} else {
$scope.class = '';
$scope.showMsg = false;
$scope.accountForm.$dirty = false;
$scope.accountForm.$pristine = true;
}
} else {
showErrorMsg(nameRequired);
}
};
$scope.submit = function(){
alert('IS Form Dirty: '+$scope.accountForm.$dirty);
};
function showErrorMsg(msg) {
$scope.class = 'error';
$scope.showMsg = true;
$scope.msg = msg;
$scope.accountForm.$dirty = true;
}
};

Resources