I am using AngularJS v1.5.8.
In html
<div class="form-group row" data-ng-repeat="friend in friends track by $index">
<label class="col-xs-1 control-label">Friend </label>
<div class="col-xs-2">
<input type="text" class="form-control" required ng-model="friend.first_name" placeholder="First Name" />
</div>
<div class="col-xs-2">
<input type="text" class="form-control" required ng-model="friend.last_name" placeholder="Last Name" />
</div>
<div class="col-xs-4">
<input type="email" class="form-control" required ng-model="friend.email" placeholder="Email" />
</div>
<div class="col-xs-2">
<input type="text" class="form-control" ng-model="friend.phone" placeholder="Phone" />
</div>
<div class="col-xs-1">
<span class="glyphicon glyphicon-plus"></span>
</div>
<div class="col-xs-1">
<span class="glyphicon glyphicon-remove"></span>
</div>
<div class="clearfix"></div>
In controller
$scope.friends = [{first_name: "", last_name: "", email: "", phone: ""}];
$scope.addMore = function () {
console.log('in add');
$scope.friends.push({
first_name: "",
last_name: "",
email: "",
phone: ""
});
};
$scope.removeFriend = function(index) {
console.log("in remove: "+index);
$scope.friends.splice(index,1);//delete last row in html form..am I expecting something wrong....
};
while I inspect the code I get removeList($index) instead I was hoping removeList(1) or removeList(4).
What possibly can be wrong?
I have two questions
- why even if I am passing index correctly , it end up deleting last element
- how data entered will be updated in angular...
If you have some tutorial to follow please share the link
I think you have some typos:
$scope.removeList = function(referIndex) {
console.log("in remove: " + referIndex); // note it is + not .
$scope.lists.splice(referIndex, 1); // note $scope.lists not $scope.list
};
Here no need to use track by index because we are not using duplicate key.
Please use below code
<div ng-app="myApp" ng-controller="myCtrl">
<div class="form-group row" data-ng-repeat="friend in friends">
<label class="col-xs-1 control-label">Friend </label>
<div class="col-xs-2">
<input type="text" class="form-control" required ng-model="friend.first_name" placeholder="First Name" />
</div>
<div class="col-xs-2">
<input type="text" class="form-control" required ng-model="friend.last_name" placeholder="Last Name" />
</div>
<div class="col-xs-4">
<input type="email" class="form-control" required ng-model="friend.email" placeholder="Email" />
</div>
<div class="col-xs-2">
<input type="text" class="form-control" ng-model="friend.phone" placeholder="Phone" />
</div>
<div class="col-xs-1">
<span class="glyphicon glyphicon-remove">Remove</span>
</div>
</div>
<div class="col-xs-1">
<span class="glyphicon glyphicon-plus">Add</span>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope)
{
$scope.friends = [{first_name: "", last_name: "", email: "", phone: ""}];
$scope.addMore = function () {
console.log('in add');
$scope.friends.push({
first_name: "",
last_name: "",
email: "",
phone: ""
});
};
$scope.removeFriend = function(index)
{
console.log("in remove: "+index);
$scope.friends.splice(index,1);//delete last row in html form..am I expecting something wrong....
};
})
</script>
Related
I'm currently trying to use jQuery to collect information from a HTML form, but I'm stuck.
Every time I console.log payload its empty and didn't capture the input values.
Questions:
Why is payload empty at the end, after I input values into the form?
how to correct it?
Should I use document.ready for this or window.onload?
Please any help is appreciated.
Here is my last attempt jQuery:
$(document).ready(function() {
const ApplyOpeningPayloadBuilder = function() {
let payload = {
"fields": []
};
return {
withKeyValue: function(key, value) {
let param = {};
param.key = key;
param.value = value;
payload.fields.push(param);
return this;
},
withFile: function(key, encoded_data, filename) {
let value = {};
value.encoded_data = encoded_data;
value.file_name = filename;
this.withKeyValue(key, value);
return this;
},
build: function() {
return payload;
}
}
}
let encoded_file = "aGVsbG8gd29ybGQ=";
let apply_for_an_opening_payload_builder = new ApplyOpeningPayloadBuilder();
$(".applicantForm input[type=text]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=email]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=tel]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=url]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
apply_for_an_opening_payload_builder.withFile("resume", encoded_file, "resume.txt");
let payload = apply_for_an_opening_payload_builder.build();
console.log("Log payload:", payload)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" id="json-response">
<div class="form-container">
<div class="header">
<h1>Application form</h1>
</div>
<form action="#" class="applicantForm">
<div class="form-group">
<div class="input-group">
<label for="First Name">First Name <span>*</span></label>
<input type="text" name="First Name">
</div>
<div class="input-group">
<label for="Last Name">Last Name <span>*</span></label>
<input type="text" name="Last Name">
</div>
</div>
<div class="form-group">
<div class="input-group">
<label for="Email">Email <span>*</span></label>
<input type="email" name="Email">
</div>
<div class="input-group">
<label for="Phone">Phone <span>*</span></label>
<input type="tel" name="Phone">
</div>
</div>
<div class="form-group">
<div class="input-group">
<label for="Resume">Resume <span>*</span></label>
<input class="form-control" type="file" name="Resume">
</div>
<div class="input-group">
<label for="LinkedIn Profile">LinkedIn Profile<span>*</span></label>
<input type="url" name="LinkedIn Profile">
</div>
<div class="input-group">
<label for="Website link">Website Link <span>*</span></label>
<input type="url" name="Website link">
</div>
<div class="input-group">
<label for="In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?"> In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?<span>*</span></label>
<input type="text" name="In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?">
</div>
</div>
<button class="submit" type="submit">Apply Now</button>
</form>
</div>
</div>
Here is the structure of how the payload object should look like in the end:
let payload = {
"fields": [
{ "key" : "candidate_first_name", "value" : "John"},
{ "key" : "candidate_last_name", "value" : "Doe"},
{ "key" : "candidate_email", "value" : "john.doe#gmail.com"},
{ "key" : "candidate_phone", "value" : "1234567890"},
{ "key" : "resume", "value": {
"encoded_data" : "aGVsbG8gd29ybGQ=",
"file_name" : "resume.txt"
}
}
]
};
Note the payload structure is from this link, specifically the "Apply for a Opening" section.
You are running all the code at once (document.ready()), instead you need to run it inside form submit, like $('.applicantForm').on('submit', function(e){}).
Check the updated fiddle
var $ = jQuery;
$(document).ready(function() {
const ApplyOpeningPayloadBuilder = function() {
let payload = {
"fields": []
};
return {
withKeyValue: function(key, value) {
let param = {};
param.key = key;
param.value = value;
payload.fields.push(param);
return this;
},
withFile: function(key, encoded_data, filename) {
let value = {};
value.encoded_data = encoded_data;
value.file_name = filename;
this.withKeyValue(key, value);
return this;
},
build: function() {
return payload;
}
}
}
let encoded_file = "aGVsbG8gd29ybGQ=";
$('.applicantForm').on('submit', function(e) {
e.preventDefault();
let apply_for_an_opening_payload_builder = new ApplyOpeningPayloadBuilder();
$(".applicantForm input[type=text]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=email]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=tel]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
$(".applicantForm input[type=url]").each(function() {
apply_for_an_opening_payload_builder.withKeyValue(this.name, this.value);
});
apply_for_an_opening_payload_builder.withFile("resume", encoded_file, "resume.txt");
let payload = apply_for_an_opening_payload_builder.build();
console.log("Log payload:", payload);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="container" id="json-response">
<div class="form-container">
<div class="header">
<h1>Application form</h1>
</div>
<form action="#" class="applicantForm">
<div class="form-group">
<div class="input-group">
<label for="First Name">First Name <span>*</span></label>
<input type="text" name="First Name">
</div>
<div class="input-group">
<label for="Last Name">Last Name <span>*</span></label>
<input type="text" name="Last Name">
</div>
</div>
<div class="form-group">
<div class="input-group">
<label for="Email">Email <span>*</span></label>
<input type="email" name="Email">
</div>
<div class="input-group">
<label for="Phone">Phone <span>*</span></label>
<input type="tel" name="Phone">
</div>
</div>
<div class="form-group">
<div class="input-group">
<label for="Resume">Resume <span>*</span></label>
<input class="form-control" type="file" name="Resume">
</div>
<div class="input-group">
<label for="LinkedIn Profile">LinkedIn Profile<span>*</span></label>
<input type="url" name="LinkedIn Profile">
</div>
<div class="input-group">
<label for="Website link">Website Link <span>*</span></label>
<input type="url" name="Website link">
</div>
<div class="input-group">
<label for="In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?"> In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?<span>*</span></label>
<input type="text" name="In lieu of a cover letter, please tell us more about why you are interested in joining the Compass Fellowship?">
</div>
</div>
<button class="submit" type="submit">Apply Now</button>
</form>
</div>
</div>
I'm using PHP 7 (Phalcon 3), Bootstrap 3 and JQuery 3. Here is my codepen. When you click on the add button it will clone the form inline.
HTML
<div class="row form-inline">
<div class="form-group col-xs-4">
<label>First name</label>
<input type="text" id="firstname" name="firstname" class="form-control">
</div>
<div class="form-group col-xs-4">
<label>Last name</label>
<input type="text" id="lastname" name="lastname" class="form-control">
</div>
<div class="form-group col-xs-4">
<label>check</label> <br>
<input type="checkbox" class="checkbox" name="check">
</div>
</div>
<button type="button" class="btn btn-primary" id="btn-add">Add</button>
JS
$("#btn-add").click(function() {
$('.row.form-inline:last').clone(true).insertAfter('.row.form-inline:last');
// Don't care about this, it's a checkbox library
$('input').iCheck({
checkboxClass: 'icheckbox_minimal-blue',
increaseArea: '20%',
checked: false
});
$('.row.form-inline:last .checkbox').iCheck('uncheck');
return false;
});
So now I need to send the data to the server but I don't know how can I create a good formatted JSON through Ajax.
I'd like to create an JSON Array based on the number of created clone like this :
[
{
"firstname" : "John",
"lastname" : "Doe",
"check" : true
},
{
"firstname" : "Mark",
"lastname" : "Davidson",
"check" : false
},
{
"firstname" : "Mike",
"lastname" : "Green",
"check" : true
}
]
And in my PHP script I gonna loop through this data easily. So how can I build this JSON array ?
Your first issue is the duplication of id attributes, which is invalid. You can change them to classes, or remove them.
Then, based on your HTML structure, you can use map() to build the array:
var data = $('.form-inline').map(function() {
var $container = $(this);
return {
firstname: $container.find('.firstname').val(),
lastname: $container.find('.lastname').val(),
checkbox: $container.find('.checkbox').prop('checked'),
}
}).get();
Here's a full working example:
$("#btn-add").on('click', function() {
$('.row.form-inline:last').clone(true).insertAfter('.row.form-inline:last');
});
$('#test').on('click', function() {
var data = $('.form-inline').map(function() {
var $container = $(this);
return {
firstname: $container.find('.firstname').val(),
lastname: $container.find('.lastname').val(),
checkbox: $container.find('.checkbox').prop('checked'),
}
}).get();
console.log(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row form-inline">
<div class="form-group col-xs-4">
<label>First name</label>
<input type="text" name="firstname" class="form-control firstname">
</div>
<div class="form-group col-xs-4">
<label>Last name</label>
<input type="text" name="lastname" class="form-control lastname">
</div>
<div class="form-group col-xs-4">
<label>check</label> <br>
<input type="checkbox" class="checkbox" name="check">
</div>
</div>
<button type="button" class="btn btn-primary" id="btn-add">Add</button>
<button id="test">Test</button>
This seems like a weird one to me. I have a form for adding vets to a dog walkers' database. I've used ng-model on each field in the form.
<div class="container-fluid" ng-show="nav.page == 'new'" ng-controller="dataController as data">
<div class="row" ng-show="nav.tab == 'vet'">
<div class="col-md-2">
</div>
<div class="col-md-8">
<h1>Add a Vet</h1>
<hr />
<form>
<div class="form-group">
<input type="text" class="form-control" placeholder="Name..." ng-model="data.creator.vet.Name"/>
</div>
<div class="form-group">
<input type="Text" class="form-control" placeholder="Address..." ng-model="data.creator.vet.Address"/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Phone Number..." ng-model="data.creator.vet.Phone"/>
</div>
<div class="form-group">
<button class="btn btn-success" ng-click="data.newVet()">Submit</button>
</div>
</form>
</div>
<div class="col-md-2">
</div>
</div>
</div>
Yesterday it was working fine, today it won't update data.creator.vet when I input data. For the life of me, I can't see any problems with it.
The js:
app.controller('dataController', function($http) {
dataCon = this;
this.creator = {};
this.creator.client = {};
this.creator.vet = {};
this.creator.client.Dogs = [];
this.allData = {};
this.newVet = function(){
console.log("New Vet Creating....")
console.log(dataCon.creator)
vet = JSON.stringify(dataCon.creator.vet);
console.log(vet);
$http.get(SERVICE_URL + "?fn=vetCreate&vet=" + vet).then(function(response) {
dataCon.init();
});
}
});
I am new to angular and am trying (and failing) to get the ngClass to work with some validation on a basic contact form.
I want to highlight the inputs when they are in the success/error by highlighting with bootstrap 'has-error' and 'glyphicon-remove' classes if there are any issues with the data.
my form is as follows;
<form class="row instant-quote-form" ng-controller="formCtrl" ng-cloak>
<div class="col-md-12">
<h2>Quick Form</h2>
<div class="form-group has-feedback">
<div class="input-group col-md-12">
<label for="titleSelect" class="input-group-addon">Title :</label>
<select name="titleSelect" id="titleSelect" class="form-control"
ng-model="form.titleResult" required>
<option value="">Select Title...</option>
<option ng-repeat="option in titles" value="{{option.name}}">{{option.name}}</option>
</select>
</div>
<div class="input-group col-md-12" ng-class="{ 'has-error': form.name.$invalid, 'text-success' : form.name.$valid}">
<label for="nameInput" class="input-group-addon">Name :</label>
<input type="text" class="form-control" id="nameInput" placeholder="Full Name..." ng-model="form.name" required>
<span ng-class="{ 'glyphicon-remove' : form.name.$invalid, 'glyphicon-ok' : form.name.$valid }" class="glyphicon form-control-feedback"></span>
</div>
<div class="input-group col-md-12">
<label for="postcodeInput" class="input-group-addon">Postcode :</label>
<input type="text" class="form-control" id="postcodeInput" placeholder="Postcode..." ng-model="form.postcode" required>
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="input-group col-md-12">
<label for="emailInput" class="input-group-addon">Email :</label>
<input type="email" class="form-control" id="emailInput" placeholder="Email Address..." ng-model="form.email" required>
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="input-group col-md-12">
<label for="telephoneInput" class="input-group-addon">Telephone :</label>
<input type="text" class="form-control" id="telephoneInput" placeholder="Telephone Number..." ng-model="form.telephone" required>
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="input-group col-md-12">
<label for="timeSelect" class="input-group-addon">To to Call :</label>
<select name="timeSelect" id="timeSelect" class="form-control"
ng-model="form.timeResult" required>
<option value="">Select Time...</option>
<option ng-repeat="option in times" value="{{option.name}}">{{option.name}}</option>
</select>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-primary btn-block" ng-click="submit(form)">Request Callback!</button>
</div>
</div>
</div>
</form>
my controller is as follows;
'use strict';
app.controller('formCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.titles =
[
{ id: '1', name: 'Mr.' },
{ id: '2', name: 'Mrs.' },
{ id: '3', name: 'Master.' },
{ id: '4', name: 'Miss.' },
{ id: '5', name: 'Sir.' },
{ id: '6', name: 'Dr.' },
{ id: '7', name: 'Other.' }
];
$scope.times =
[
{ id: '1', name: 'Morning.' },
{ id: '2', name: 'Afternoon.' }
];
$scope.submit = function (form) {
console.log(form);
};
}]);
However, the ngclass directive is not being applied? also it seems that the submit is being called even when the form is invalid? do I need to validate the form fromthe controller as well?
Add a name attribute and value to your form tag & input...
<form name="form" class="row instant-quote-form" ng-controller="formCtrl" ng-cloak>
&
<input name="name" type="text" class="form-control" id="nameInput" placeholder="Full Name..." ng-model="name" required>
because when you refer to form.name in 'has-error': form.name.$invalid it works based off of the name of the form and the name of the input box
Note there is a conflict using form.name as your ng-model based upon your controller you will want ng-model="name"
Here is a working plnkr
I have an angular sign-up page. This is the directory structure of my project:
singUpPage-Angular
bin
bower_components
model
mongodbApp.js
node_modules
**partials
fail.html
main.html
success.html**
public
images
**javascripts
signUp.js**
stylesheets
routes
index.js
users.js
**views
index.ejs**
app.js
package.json
All my html is in partials folder
The javascript controller code is in signup.js
The main html is in views index.ejs.
I have tried to acces the html using the ui router and the code is not working. I am not sure if itis an error with the path or if there is a prolem with ui-router code.
The router does not take me to the page:
When I run the code: on the address bar I get: http://localhost:3000/#/partials/main.html: but nothing from the main page get displayed. I dont seem to get an errors either.
index.ejs
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="/angular/angular.js"></script>
<script src="/ui-router/release/angular-ui-router.min.js"></script>
<script src="/javascripts/signUp.js"></script>
</head>
<body ng-controller="myCtrl">
<div ui-view></div>
</body>
</html>
signUp.js
angular.module("myApp",['ui.router'])
.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('partials/main.html');
$stateProvider
.state('success', {
url: "/success",
templateUrl:'partials/success.html'
})
.state('fail', {
url: '/fail',
templateUrl:'partials/fail.html'
})
})
.controller("myCtrl", function($scope, SignUp,$state){
$scope.clearPerson = function(){
$scope.first = "";
$scope.last = "";
$scope.email = "";
$scope.password = "";
$scope.confirm = "";
$scope.dob = "";
}
$scope.addPerson = function(){
/* console.log($scope.first);
console.log($scope.last);
console.log($scope.email);
console.log($scope.password);
console.log($scope.confirm);
console.log($scope.dob);*/
$scope.person = {
firstName: $scope.first,
lastName: $scope.last,
email: $scope.email,
password:$scope.password,
dateOfBirth: $scope.dob
}
console.log($scope.person);
SignUp.add($scope.person).success(function(res){
$state.go("success");
console.log(res);
}).error(function(res){
$state.go("fail");
console.log("error");
})
}
})
.factory("SignUp", function($http){
return{
add: function(person){
return $http.post('/signup',person);
}
}
})
main.html
<h1>Sign up Page</h1>
<div class="new-container">
<div class="container">
<h3>Create an ID</h3>
<form class="form-horizontal" name="signup" novalidate ng-submit="addPerson()">
<div class="form-group">
<h4>Name</h4>
<label class="col-sm-2 label-control align-text" >First Name</label>
<div class="col-sm-4 text-margin" >
<input name="first" ng-maxlength=50 ng-model="first" type="text" class="form-control" required>
<div class="error"
ng-show="signup.first.$dirty && signup.first.$invalid">
<small class="error"
ng-show="signup.first.$error.required">
Your name is required.
</small>
<small class="error"
ng-show="signup.first.$error.maxlength">
Your name cannot be longer than 50 characters
</small>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 label-control align-text" >Last Name</label>
<div class="col-sm-4 text-margin">
<input name="last" ng-maxlength=50 ng-model="last" type="text" class="form-control" placeholder="optional">
<div class="error"
ng-show="signup.last.$dirty && signup.last.$invalid">
<small class="error"
ng-show="signup.last.$error.maxlength">
Your name cannot be longer than 50 characters
</small>
</div>
</div>
</div>
<div class="form-group">
<h4>ID and Password</h4>
<label class="col-sm-2 align-text label-control">Username</label>
<div class="col-sm-4 text-margin">
<input name="email" ng-maxlength=56 ng-model="email" type="email" class="form-control" placeholder="Email" required>
<div class="error"
ng-show="signup.email.$dirty && signup.email.$invalid">
<small class="error"
ng-show="signup.email.$error.required">
Your email is required.
</small>
<small class="error"
ng-show="signup.email.$error.maxlength">
Your name cannot be longer than 56 characters
</small>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 label-control align-text">Password</label>
<div class="col-sm-4 text-margin">
<input name="password" ng-minlength=6 ng-model="password" type="password" class="form-control al" placeholder="Password" required>
<div class="error"
ng-show="signup.password.$dirty && signup.password.$invalid">
<small class="error"
ng-show="signup.password.$error.required">
Your password is required.
</small>
<small class="error"
ng-show="signup.password.$error.minlength">
Your name cannot be atleast 6 characters long.
</small>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 label-control align-text">Confirm Password</label>
<div class="col-sm-4 text-margin">
<input name="confirm" compare-to="password" ng-model="confirm" type="password" class="form-control" placeholder="Password" required>
<div class="error"
ng-show="signup.confirm.$dirty && signup.confirm.$invalid">
<small class="error"
ng-show="signup.confirm.$error.required">
Password confirmation is required.
</small>
<small class="error"
ng-show="signup.confirm.$error.errorCompareTo">
Your passwords do not match.
</small>
</div>
</div>
</div>
<div class="form-group">
<h4>Date of Birth</h4>
<label class="col-sm-2 label-control align-text">Birthday</label>
<div class="col-sm-4 text-margin">
<input ng-model="dob" type="date" class="form-control" placeholder="MM/DD/YYYY" required>
</div>
</div>
<div class="form-group" >
<div class="col-sm-offset-2 col-sm-10 float-right" >
<button type="submit" class="btn signUp" >Sign Up</button>
<button type="submit" class="btn btn-default" ng-click="clearPerson()">Clear</button>
</div>
</div>
</form>
</div>
</div>
fail.html
<h1>fail</h1>
success.html
<h1>success</h1>
Do this
$urlRouterProvider.otherwise('/');
In State
$stateProvider
.state('main', {
url: "/",
templateUrl:'partials/main.html'
})
This will open your signUpPage