How to prevent adding existing email to table row in angularjs - javascript

I want to prevent adding an email address which already exists.
I want to disable adding more than 5 email addresses and names.
This is controller.js:
var helloApp = angular.module("helloApp", []);
helloApp.controller("CompanyCtrl", function($scope) {
$scope.companies = [
{ 'name':'Infosys Technologies',
'email': 'firstdawn1994#gmail.com',},
{ 'name':'Cognizant Technologies',
'email': 'cognizant#gmail.com',},
{ 'name':'Wipro',
'email': 'wipro#gmail.com',},
{ 'name':'Tata Consultancy Services (TCS)',
'email': 'tata#gmail.com',},
{ 'name':'HCL Technologies',
'email': 'hcl#gmail.com',},
];
$scope.addRow = function(){
$scope.companies.push({ 'name':$scope.name, 'email': $scope.email });
$scope.name='';
$scope.email='';
};
$scope.removeRow = function(name){
var index = -1;
var comArr = eval( $scope.companies );
for( var i = 0; i < comArr.length; i++ ) {
if( comArr[i].name === name ) {
index = i;
break;
}
}
if( index === -1 ) {
alert( "Something gone wrong" );
}
$scope.companies.splice( index, 1 );
};
});
This is the HTML:
<html ng-app="helloApp">
<head>
<title>Hello AngularJS - Add Table Row Dynamically</title>
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script
src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script
src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
<script src="js/controllers.js"></script>
</head>
<!-- Controller name goes here -->
<body ng-controller="CompanyCtrl">
<input type="submit" value="Add New User +" class="btn btn-primary" id="add_user" />
<form class="form-horizontal" role="form" ng-submit="addRow()" id="submit_form">
<div class="form-group">
<label class="col-md-2 control-label">Name</label>
<div class="col-md-4">
<input type="text" class="form-control" name="name"
ng-model="name" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Email</label>
<div class="col-md-4">
<input type="text" class="form-control" name="email"
ng-model="email" />
</div>
</div>
<div class="form-group">
<div style="padding-left:110px">
<input type="submit" value="Submit" class="btn btn-primary"/>
</div>
</div>
</form>
<table class="table">
<tr>
<th>Name
</th>
<th>Email
</th>
</tr>
<tr ng-repeat="company in companies | limitTo : 5">
<td>{{company.name}}
</td>
<td>{{company.email}}
</td>
<td>
<input type="button" value="Remove" class="btn btn-primary" ng-click="removeRow(company.name)"/>
</td>
</tr>
</table>
<script type="text/javascript">
$(document).ready(function() {
$('#submit_form').hide();
$('#add_user').click(function(event) {
$('#submit_form').toggle(1000);
});
});
</script>
</body>
</html>

To achieve this please modify your addRow function to this code below
$scope.addRow = function(){
//store the new company in a variable for easy reference
var newCompany = { 'name':$scope.name, 'email': $scope.email };
//loops through existing companies to check if the email exists already
var emailExists = $scope.companies.some(function(item){
return item.email === newCompany.email;
});
//validation check before inserting the new company.
if( $scope.companies.length < 5 && !emailExists){
$scope.companies.push(newCompany);
$scope.name='';
$scope.email='';
}else{
//display some validation messages
}
};
Also in your HTML, you can disable the Add button so that the user does not have the opportunity to add more Companies if you already have up to 5 companies by adding the attribute below the button to:
data-ng-disable="companies.length > 5"
Hence, the button becomes:
<input type="submit" data-ng-disable="companies.length > 5" value="Submit" class="btn btn-primary"/>
Hope this helps

Related

Is there a way where I can disable my button "Insert" when error appears?

Newbie here. Hello, my target is when error shows up (Not enough balance), the INSERT button will be disabled. I have a input type number whose value must be less than equal to the current wallet, If it's greater than, then error will appear. I have provided the snippet below.
SCRIPT:
$( document ).ready(function() {
$("#box").keyup( function(){
var betAmount = $("#box").val();
var walletAmount = 500; // your session data goes here
var remainingAmount = walletAmount - betAmount;
$("#betAmountResult").text(remainingAmount >=0 ? remainingAmount : 'Error, not enough balance');
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
<form method="POST" action="<?php echo base_url();?>auth/form_validation">
<input type="number" placeholder="Enter Amount" name="bet" class="form-control" id="box" required>
<!-- change id's name to betAmount -->
<p>CURRENT WALLET: <a style="color:blue;">500</a></p>
<p class="remaining">REMAINING BALANCE:
<a class="p-1" id="betAmountResult"></a></p>
<input type="submit" name="insert" value="Insert">
</div>
</form>
$(document).ready(function() {
$("#box").keyup(function() {
var betAmount = $("#box").val();
var walletAmount = 500; // your session data goes here
var remainingAmount = walletAmount - betAmount;
if (remainingAmount >= 0) {
$("#betAmountResult").text(remainingAmount);
$("#insert").attr('disabled', false);
} else {
$("#insert").attr('disabled', true);
$("#betAmountResult").text('Error, not enough balance');
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<form method="POST" action="<?php echo base_url();?>auth/form_validation">
<input type="number" placeholder="Enter Amount" name="bet" class="form-control" id="box" required>
<!-- change id's name to betAmount -->
<p>CURRENT WALLET: <a style="color:blue;">500</a></p>
<p class="remaining">REMAINING BALANCE:
<a class="p-1" id="betAmountResult"></a>
</p>
<input type="submit" id="insert" name="insert" value="Insert">
</div>
</form>
Like this
.prop("disabled",not enough)
.prop() vs .attr()
or to remove
.toggle(enough)
I added an ID to the button to access it directly
I also use .on("input" which is more generic (handles paste for example)
$(function() {
$("#box").on("input",function() {
const betAmount = $("#box").val(),
walletAmount = 500, // your session data goes here
remainingAmount = walletAmount - betAmount,
enough = remainingAmount >= 0;
$("#betAmountResult").text(enough ? remainingAmount : 'Error, not enough balance');
$("#insert").prop("disabled",!enough); // disable
// $("#insert").toggle(enough); // remove
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<form method="POST" action="<?php echo base_url();?>auth/form_validation">
<input type="number" placeholder="Enter Amount" name="bet" class="form-control" id="box" required>
<!-- change id's name to betAmount -->
<p>CURRENT WALLET: <a style="color:blue;">500</a></p>
<p class="remaining">REMAINING BALANCE:
<a class="p-1" id="betAmountResult"></a>
</p>
<input type="submit" name="insert" id="insert" value="Insert">
</div>
</form>

how to add multi captcha in same page and check both checkbox its fill

I have two forms on a single page, one of them is a login form and the other is a register form (two tabs) and I want to check the the captchas, but when I click the check captcha from register form I can't login.
The login form:
HTML:
<div id="loginUserTab" class="tab-pane fade">
<form>
<div class="form-group login-width-100">
<label for="id_number" class="m-rtl-label"><span class="requiredMark">*</span>passport number:</label>
<input type="text" class="form-control" id="pNo" name="pNo" data-validetta="required,minLength[10],maxLength[10]" lang="fa" style="text-align: left;">
</div>
<div class="form-group login-width-100">
<label for="mNumber" class="m-rtl-label"><span class="requiredMark"></span> telephone :</label>
<input type="text" class="form-control" id="tNumber" name="tNumber" data-validetta="required,minLength[11],maxLength[11]" lang="fa" style="text-align: left;">
</div>
<div class="form-group" style="float:right;padding-right: 20px;">
<div class="g-recaptcha" data-sitekey="...."></div>
</div>
<div class="form-group login-width-100">
<button type="submit" class="btn btn-primary colorGreenBTN">login</button>
</div>
</form>
</div>
JS:
var v = grecaptcha.getResponse();
if (v.length == 0) {
alert("fill the form");
return;
} else if (!$("#Terms").prop("checked")) {
alert("check the rules");
}
Simplest Way to validate as much g-captcha validate
Hope you have included api.js before </head> tag as per below
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit"></script>
Your HTML Code looks like below
<div class="g-recaptcha-contact" data-sitekey="Your Site Key" id="RecaptchaField2"></div>
<input type="hidden" class="hiddenRecaptcha" name="ct_hiddenRecaptcha" id="ct_hiddenRecaptcha">
<div class="g-recaptcha-quote" data-sitekey="Your Site Key" id="RecaptchaField1"></div>
<input type="hidden" class="hiddenRecaptcha" name="qt_hiddenRecaptcha" id="qt_hiddenRecaptcha">
After you add this code in footer with tag
var CaptchaCallback = function() {
var widgetId1;
var widgetId2;
widgetId1 = grecaptcha.render('RecaptchaField1', {'sitekey' : 'Your Site Key', 'callback' : correctCaptcha_quote});
widgetId2 = grecaptcha.render('RecaptchaField2', {'sitekey' : 'Your Site Key', 'callback' : correctCaptcha_contact});
};
var correctCaptcha_quote = function(response) {
$("#qt_hiddenRecaptcha").val(response);
};
var correctCaptcha_contact = function(response) {
$("#ct_hiddenRecaptcha").val(response);
};
And Last easy step for developer add Jquery Validation as per below
$("#form_id").validate({
ignore: [],
rules: {
ct_hiddenRecaptcha: { required: true, },
qt_hiddenRecaptcha: { required: true, },
},
});
If you have same class for both the forms, you can use it to validate above.

login form validation javascript - value not present in $_POST

I am trying to validate the form with id's username and initial_password: The HTML portion is as:
<form name="myform" action="includes/logincontrol.php" method="POST" onsubmit="return validateForm()">
<div class="form-group"> <!-- User ID Field -->
<label id="user_name_error" >User ID:</label>
<input class="form-control" id="username" type="text" onfocusout ="validateUserName()"/>
</div>
<div class="form-group"> <!-- Password Field -->
<label id="password_error">Password: </label>
<input class="form-control" id="initial_password" type="password" onfocusout ="validatePassword()"/>
</div>
<div class="form-group"> <!-- Register -->
<p id="submit-error"></p>
<hr/>
<button class="btn btn-primary" id="login" type="submit">Login</button>
<input class="btn btn-danger" type="reset" value="Reset" onClick="clearfunc()"/>
<hr/>
<button type="button" class="btn btn-success" onclick="window.location.href = 'register_user.php'">Register</button>
<button type="button" class="btn btn-warning" onclick="window.location.href = 'changepw.php'">Change Password</button>
</div>
</form>
Java Script:
function validateUserName() {
var user_name_entered = document.getElementById('username').value;
if (user_name_entered.length === 0) {
producePrompt('User empty?', 'user_name_error', 'red');
document.getElementById('login').disabled = true;
return false;
}
producePrompt('User Name OK!', 'user_name_error', 'green');
document.getElementById('login').disabled = false;
return true;
}
function validatePassword() {
var password_entered = document.getElementById('initial_password').value;
if (password_entered.length === 0) {
producePrompt('Password empty?', 'password_error', 'red');
document.getElementById('login').disabled = true;
return false;
}
producePrompt('Password Entered!', 'password_error', 'green');
document.getElementById('login').disabled = false;
return true;
}
function producePrompt(message, promptLocation, color) {
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;
}
I am unable to get the elements in $_POST array. Please help
You have to put name at inputs, to access them with $_POST.
<input name="usernameInput" class="form-control" id="username" type="text" onfocusout ="validateUserName()"/>
<?php
$username = $_POST['usernameInput'];
?>
If you want to see if the form is submited put a name in the type submit input and try this:
if (isset($_POST['submitButton']) {
$username = $_POST['usernameInput'];
#..etc
}

Angular JS filter Search

I want to retain the selected check boxes as is even when I am
changing my search query. Initially I am posting some query in search
and selecting one of the resulted values, Now if I change my search
query, then New values will be my result. But I want to retain the
checkbox selected for the previous values...
`
//Demo of Searching and Sorting Table with AngularJS
var myApp = angular.module('myApp',[]);
myApp.controller('TableCtrl', ['$scope', function($scope) {
$scope.allItems = getDummyData();
$scope.resetAll = function()
{
$scope.filteredList = $scope.allItems ;
$scope.newEmpId = '';
$scope.newName = '';
$scope.newEmail = '';
$scope.searchText = '';
}
$scope.add = function()
{
$scope.allItems.push({EmpId : $scope.newEmpId, name : $scope.newName, Email:$scope.newEmail});
$scope.resetAll();
}
$scope.search = function()
{
$scope.filteredList = _.filter($scope.allItems,
function(item){
return searchUtil(item,$scope.searchText);
});
if($scope.searchText == '')
{
$scope.filteredList = $scope.allItems ;
}
}
$scope.resetAll();
}]);
/* Search Text in all 3 fields */
function searchUtil(item,toSearch)
{
/* Search Text in all 3 fields */
return ( item.name.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 || item.Email.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 || item.EmpId == toSearch
)
? true : false ;
}
/*Get Dummy Data for Example*/
function getDummyData()
{
return [
{EmpId:2, name:'Jitendra', Email: 'jz#gmail.com'},
{EmpId:1, name:'Minal', Email: 'amz#gmail.com'},
{EmpId:3, name:'Rudra', Email: 'ruz#gmail.com'}
];
}
.icon-search{margin-left:-25px;}
<br /> <br />
<div ng-app="myApp">
<div ng-controller="TableCtrl">
<div class="input-group">
<input class="form-control" ng-model="searchText" placeholder="Search" type="search" ng-change="search()" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-search"></span>
</span>
</div>
<table class="table table-hover data-table sort display">
<thead>
<tr>
<th class="EmpId"> <a href="" ng-click="columnToOrder='EmpId';reverse=!reverse">EmpId
</a></th>
<th class="name"> Name </th>
<th class="Email"> Email </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in filteredList | orderBy:columnToOrder:reverse">
<td><input type="checkbox" name="test" />{{item.EmpId}}</td>
<td>{{item.name}}</td>
<td>{{item.Email}}</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-xs-3">
<input type="text" ng-model="newEmpId" class="form-control" placeholder="EmpId">
</div>
<div class="col-xs-3">
<input type="text" ng-model="newName" class="form-control" placeholder="Name">
</div>
<div class="col-xs-4">
<input type="email" ng-model="newEmail" class="form-control" placeholder="Email">
</div>
<div class="col-xs-1">
<button ng-click="add()" type="button" class="btn btn-primary">
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
</div> <!-- Ends Controller -->
</div>
`Fiddle
Try to add ng-model="item.selected" to your checkbox tag
<td><input ng-model="item.selected" type="checkbox" name="test" />{{item.EmpId}}</td>
Works for me, hope it helps.
Looks like this is happening because you are resetting the items here:
if($scope.searchText == '')
{
$scope.filteredList = $scope.allItems ;
}
and allItems doesn't tell anywhere if the checkbox needs to be selected on not. I would suggest you to update the code where you are creating the checkboxes, something like:
<td><input type="checkbox" name="test" ng-model=item.selected ng-checked=item.selected/>
Note that I have updated the item to have a 'selected' field which will tell if that item is selected or not(default could be false). While creating the checkbox I have linked the model using ng-model=item.selected
Updated fiddle at http://jsfiddle.net/3a3zD/194/

Sharing data between different controllers

I want to build a small application (for learning Angular JS) that can define a list of locations and a list of events. The application was developed based on the tutorial found here: http://g00glen00b.be/prototyping-spring-boot-angularjs/.
When defining a new event I would like to associate a location for the new event. The location should be selected using a combobox.
So first I define 2 locations, let's say Location 1 and Location 2. I want to bind somehow the list of available locations (1 and 2) to the combobox labeled "Location select" see this image
So far I was able to bind the location list to the combobox, but the items of the combobox are updated only when I refresh the browser. I would like to be able to automatically refresh the content of the combobox whenever the list of available locations is changed (a new location is added or a location is removed).
Here is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet"
href="./bower_components/bootstrap-css-only/css/bootstrap.min.css" />
</head>
<body ng-app="myEventApp">
<div class="container" ng-controller="EventAppController" >
<div class="page-header">
<h1>Edit Events</h1>
</div>
<div class="alert alert-info" role="alert"
ng-hide="events && events.length > 0">There are no events yet.
</div>
<form class="form-horizontal" role="form"
ng-submit="addEvent(newEventName,newEventDescription)" ng-controller="LocationAppController">
<div >Locations: {{locations}}</div>
<div class="form-group" ng-repeat="event in events">
<div class="checkbox col-xs-9">
<label> <strong>{{event.name}}</strong> /
{{event.description}}
</label>
</div>
<div class="col-xs-3">
<button class="pull-right btn btn-danger" type="button"
title="Delete" ng-click="deleteEvent(event)">
<span class="glyphicon glyphicon-trash"></span>
</button>
</div>
</div>
<hr />
<div class="input-group">
<input type="text" class="form-control" ng-model="newEventName"
placeholder="Enter the name..." /> <input type="text"
class="form-control" ng-model="newEventDescription"
placeholder="Enter the description..." />
<label for="locationSelect">Location select: </label>
<select
name="locationSelect" id="locationSelect" ng-model="data.repeatSelect">
<option value="">---Please select---</option>
<option ng-repeat="location in locations"
value="{{location.id}}">{{location.name}}</option>
</select>
<div class="col-md-6"></div>
<span class="input-group-btn">
<button class="btn btn-default" type="submit"
ng-disabled="!newEventName||!newEventDescription" title="Add">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</form>
</div>
<!-- Location -->
<div class="container" ng-controller="LocationAppController">
<div class="page-header">
<h1>Edit Locations</h1>
</div>
<div class="alert alert-info" role="alert"
ng-hide="locations && locations.length > 0">There are no
locations defined yet.</div>
<form class="form-horizontal" role="form"
ng-submit="addLocation(newLocationName,newLocationAddress)">
<div class="form-group" ng-repeat="location in locations">
<div class="checkbox col-xs-9">
<label> <strong>{{location.name}}</strong> /
{{location.address}}
</label>
</div>
<div class="col-xs-3">
<button class="pull-right btn btn-danger" type="button"
title="Delete" ng-click="deleteLocation(location)">
<span class="glyphicon glyphicon-trash"></span>
</button>
</div>
</div>
<hr />
<div class="input-group">
<input type="text" class="form-control" ng-model="newLocationName"
placeholder="Enter the name..." /> <input type="text"
class="form-control" ng-model="newLocationAddress"
placeholder="Enter the address..." />
<!-- <label>Location: </label> -->
<!-- <select -->
<!-- name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect"> -->
<!-- <option ng-repeat="option in data.availableOptions" -->
<!-- value="{{option.id}}">{{option.name}}</option> -->
<!-- </select> -->
<div class="col-md-6"></div>
<span class="input-group-btn">
<button class="btn btn-default" type="submit"
ng-disabled="!newLocationName||!newLocationAddress" title="Add">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</form>
</div>
<script type="text/javascript"
src="./bower_components/angular/angular.min.js"></script>
<script type="text/javascript"
src="./bower_components/angular-resource/angular-resource.min.js"></script>
<script type="text/javascript"
src="./bower_components/lodash/dist/lodash.min.js"></script>
<script type="text/javascript" src="./app/eventApp.js"></script>
<script type="text/javascript" src="./app/eventControllers.js"></script>
<script type="text/javascript" src="./app/eventServices.js"></script>
<script type="text/javascript" src="./app/locationControllers.js"></script>
<script type="text/javascript" src="./app/locationServices.js"></script>
<script type="text/css" src="./app/custom.css"></script>
</body>
</html>
And these are the controllers used:
eventControllers.js
(function(angular) {
var EventAppController = function($scope, Event) {
Event.query(function(response) {
$scope.events = response ? response : [];
});
$scope.addEvent = function(name, description) {
new Event({
locations:[],
name : name,
description : description,
}).$save(function(event) {
$scope.events.push(event);
});
$scope.newEventName = "";
$scope.newEventDescription = "";
};
$scope.updateEvent = function(event) {
event.$update();
};
$scope.deleteEvent = function(event) {
event.$remove(function() {
$scope.events.splice($scope.events.indexOf(event), 1);
});
};
};
EventAppController.$inject = [ '$scope', 'Event' ];
angular.module("myEventApp.controllers").controller("EventAppController",
EventAppController);
}(angular));
locationControllers.js
(function(angular) {
var LocationAppController = function($scope, Location) {
Location.query(function(response) {
$scope.locations = response ? response : [];
});
$scope.addLocation = function(name, address) {
new Location({
name: name,
address: address,
}).$save(function(location) {
$scope.locations.push(location);
});
$scope.newLocationName = "";
$scope.newLocationAddress = "";
};
$scope.updateLocation = function(location) {
location.$update();
};
$scope.deleteLocation = function(location) {
location.$remove(function() {
$scope.locations.splice($scope.locations.indexOf(location), 1);
});
};
return {
getLocations: function() {
return $scope.locations;
}
}
};
LocationAppController.$inject = ['$scope', 'Location'];
angular.module("myEventApp.controllers").controller("LocationAppController", LocationAppController);
}(angular));
eventServices.js
(function(angular) {
var EventFactory = function($resource) {
return $resource('/event/:id', {
id : '#id'
}, {
update : {
method : "PUT"
},
remove : {
method : "DELETE"
}
});
};
EventFactory.$inject = [ '$resource' ];
angular.module("myEventApp.services").factory("Event", EventFactory);
}(angular));
locationServices.js
(function(angular) {
var LocationFactory = function($resource) {
return $resource('/location/:id', {
id : '#id'
}, {
update : {
method : "PUT"
},
remove : {
method : "DELETE"
}
});
};
LocationFactory.$inject = [ '$resource' ];
angular.module("myEventApp.services").factory("Location", LocationFactory);
}(angular));
So, the question is: how to automatically update the content of the combobox when a new location is added / a location is deleted? Thank you.

Categories

Resources