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>
Related
I have an HTML form that I wanna to use to generate dynamically ADD more input fields:
<div class="row cloneDefault">
<div class="form-group col-md-1">
<br />
<h4 style="text-align:right">1.</h4>
</div>
<div class="form-group col-md-1">
<label class="control-label">First name</label>
<input type="text" value='' class="form-control" id="FirstnameField"/>
</div>
<div class="form-group col-md-2">
<label for="sname" class="control-label">last name</label>
<input type="text" value='' class="form-control" id="lastnameField"/>
</div>
<i class="remove">remove</i>
</div>
<form class="frm">
<div class="row">
<div class="form-group col-md-1">
<br />
<h4 style="text-align:right">1.</h4>
</div>
<div class="form-group col-md-1">
<label for="fname" class="control-label">First name</label>
<input type="text" value='' class="form-control" id="fname"/>
</div>
<div class="form-group col-md-2">
<label for="sname" class="control-label">last name</label>
<input type="text" value='' class="form-control" id="sname"/>
</div>
<i class="remove">remove</i>
</div>
<i class="add"> Add </i>
</form>
<style>
.cloneDefault{
display: none;
}
</style>
And JS to handle adding input fields dynamically:
$(document).ready(function() {
$(".add").click(function() {
$(".cloneDefault").clone(true).insertBefore(".frm > div:last-child");
$(".frm > .cloneDefault").removeClass("cloneDefault");
return false;
});
$(document).on('click', '.remove', function() {
$(this).parent().remove();
});
});
Now, I can easily retrieve text value from an input field by element id and then query cloud firestore:
const first_name = document.querySelector('#fname').value;
const last_name = document.querySelector('#sname').value;
firebase.firestore().collection("users").add({
fame: first_name,
sname: last_name,
}).then(function () {
console.log("success");
})
.catch(function (error) {
console.log("error:", error);
});
But how to save dynamically generated input fields in JS and save them on cloud firestore? I realised that my code to generate dynamically added input data may be unsuitable if I'd like to use it afterwards. What I wanted to do is similiar as this . Any idea?
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 have a registration form that I would like to have multiple field validation. What I mean by this is if more than one field is not filled in it will be highlighted red. I have some code already written but instead of highlighting the field not filled in, it's highlighting all of them. I realise it is quite long winded but I'm fairly new to this. My JS code is as follows:
`function formCheck() {
var val = document.getElementById("fillMeIn").value;
var val = document.getElementById("fillMeIn2").value;
var val = document.getElementById("fillMeIn3").value;
var val = document.getElementById("fillMeIn4").value;
var val = document.getElementById("fillMeIn5").value;
var val = document.getElementById("fillMeIn6").value;
var val = document.getElementById("fillMeIn7").value;
if (val == "") {
alert("Please fill in the missing fields");
document.getElementById("fillMeIn").style.borderColor = "red";
document.getElementById("fillMeIn2").style.borderColor = "red";
document.getElementById("fillMeIn3").style.borderColor = "red";
document.getElementById("fillMeIn4").style.borderColor = "red";
document.getElementById("fillMeIn5").style.borderColor = "red";
document.getElementById("fillMeIn6").style.borderColor = "red";
document.getElementById("fillMeIn7").style.borderColor = "red";
return false;
}
else {
document.getElementById("fillMeIn").style.borderColor = "green";
document.getElementById("fillMeIn2").style.borderColor = "green";
document.getElementById("fillMeIn3").style.borderColor = "green";
document.getElementById("fillMeIn4").style.borderColor = "green";
document.getElementById("fillMeIn5").style.borderColor = "green";
document.getElementById("fillMeIn6").style.borderColor = "green";
document.getElementById("fillMeIn7").style.borderColor = "green";
}
}`
My HTML is as follows:
'<form id="mbrForm" onsubmit="return formCheck();" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" class="form-control" placeholder="First Name" >
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" class="form-control" placeholder="Last Name" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" class="form-control vertical-gap" placeholder="First Line" >
<input id="fillMeIn4" type="text" class="form-control vertical-gap" placeholder="Second Line" >
<input id="fillMeIn5" type="text" class="form-control vertical-gap" placeholder="Town/City" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" class="form-control vertical-gap" placeholder="Postcode" >
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" class="form-control vertical-gap" placeholder="Email address" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<!--<button type="button" input type="hidden" class="btn btn-success" name="redirect" value="thanks.html">SUBMIT</button>-->
<input type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>'
Thanks!
You could have the ids in an Array, iterate through its values, and execute the repeatable code in a function that groups all the logic inside.
example :
["fillMeIn1", "fillMeIn2", "fillMeIn3", "fillMeIn4"].each(function(id){
// do things with id
})
Why not use the html "required" property instead?
If you want to do this with JS, you should give each variable a different name. In the code you posted you are continuously overwriting the same variable, and then, it evaluates val (which ended up being assigned to the (fill me7 value) to "", and if true, setting all the borders to red.
Set different variables, push the input values into an array when submit is triggered and loop through them if variables[i]==0, set getElementId(switch case[i] or another array with the name of the inputs[i]).bordercolor to red.
AGAIN, this sound VERY INEFFICIENT and I am not sure at all it would work. My guess is that it would take A LOT of time, and probably get timed out (except you are using some asych/try-catch kind of JS).
I would simply go for an HTML required property and then override the "required" property in CSS to make it look as you intend to. Simpler, easy and clean.
The main issue in your code is that you override the variable val each time you wrote var val = ....
Keeping your own your logic, you could write something like that.
var formModule = (function () {
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
function markInvalid($field) {
$field.style.borderColor = 'red';
}
function markValid($field) {
$field.style.borderColor = 'green';
}
return {
check: function () {
var isValid = true;
$fields.forEach(function ($f) {
if ($f.value === '') {
if (isValid) alert('Please fill in the missing fields');
isValid = false;
markInvalid($f);
}
else markValid($f);
});
return isValid;
}
};
})();
There are some extra concepts in this example which may be useful:
Working with the DOM is really slow, that's why you should
put your elements in a variable once for all and not everytime you
click on the submit button.
In my example i wrap the code with var formModule = (function () {...})();.
It's called module pattern. The goal is to prevent variables to leak in the rest of the application.
A better solution could be this one using the 'power' of html form validation:
HTML:
<form id="mbrForm" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" required class="form-control" placeholder="First Name">
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" required class="form-control" placeholder="Last Name">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" required class="form-control vertical-gap" placeholder="First Line">
<input id="fillMeIn4" type="text" required class="form-control vertical-gap" placeholder="Second Line">
<input id="fillMeIn5" type="text" required class="form-control vertical-gap" placeholder="Town/City">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" required class="form-control vertical-gap" placeholder="Postcode">
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" required class="form-control vertical-gap" placeholder="Email address">
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<input id="btnSubmit" type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>
JS:
var formModule = (function () {
var $form = document.getElementById('mbrForm');
var $btn = document.getElementById('btnSubmit');
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
checkValidation();
$form.addEventListener('change', checkValidation);
$form.addEventListener('keyup', checkValidation);
$fields.forEach(function ($f) {
$f.addEventListener('change', function () {
markInput($f, $f.checkValidity());
});
});
function checkValidation() {
$btn.disabled = !$form.checkValidity();
}
function markInput($field, isValid) {
$field.style.borderColor = isValid ? 'green' : 'red';
}
})();
In this example, the button gets disabled until the form is valid and inputs are validated whenever they are changed.
I added required attribute in HTML inputs so they can be handled by native javascript function checkValidity(). Note that in this case inputs email and number are also correctly checked. You could also use attribute pattern to get a more powerfull validation:
<input type="text" pattern="-?[0-9]*(\.[0-9]+)?">
Hope it helps.
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>
The html inside contact_info div is appended dynamically using jquery append function (multiple contact person can exist). How can I produce following json format from the input using jquery?
{
"Company":[
{
"company_name":"ABC Company",
"contact_info":[
{
"contact_person":"Mr. ABC",
"email":"abc#def.com"
},
{
"contact_person":"Mr. XYZ",
"email":"xyz#def.com"
}
]
}
]
}
<div class="form-group">
<label>Company Name
</label>
<div class="col-md-5">
<input name="company_name" id="company_name" type="text" class="form-control">
</div>
</div>
<div id="contact_info">
<div class="row">
<div class="form-group">
<div class="row">
<label>Contact Person
</label>
<input name="contact_person" id="contact_person" type="text" class="form-control" maxlength="100">
<label>Email
</label>
<input type="email" name="cp_email" id="cp_email" class="form-control" maxlength="100">
</div>
</div>
</div>
</div>
<button onclick="addCompany()">Add Company</button>
-----------Script------------
var company=[];
function addCompany()
{
var pushed=0;
$.each(company, function(i, data) {
if(data.company_name===$('#company_name').val())
{
company[i].contact_info.push({
"contact_person":$('#contact_person').val(),
"email":$('#cp_email').val()
});
pushed++;
return false;
}
});
if(pushed==0)
{
var obj={
"company_name":$('#company_name').val(),
"contact_info":[
{
"contact_person":$('#contact_person').val(),
"email":$('#cp_email').val()
}
]
};
company.push(obj);
}
alert(JSON.stringify(company));
}