How to pass multiple forms serialized Object to an array Jquery - javascript

I have multiple forms and I am doing the serialized array of my form.
Expectation:
I need to create an temporary object and I need to pass all the values of my form values into that object.
So in the below Code I have create a temp object tmpObj, i am trying to push all the iterated form values into the fields which are under tmpObj.
tmpObj has multiple attributes like field 1 and field 2, and it has attributes like firstname and lastname.
and i need to push this tmpObj to the items array.
My form has firstname and lastname, i need to iterate this forms and get the values of the firstname and lastname and i need to push it to the object and the object should be pushed to the items array.
But If am doing the serialize array, am able to push either firstname or lastname, only in firstname field.
Expected Output:
{
"items": [
{
"fieldset": {
"field1": {
"firstName": "abc",
"lastName": "def"
}
},
"field2": {
"firstName": "abc",
"lastName": "def"
}
},
{
"fieldset": {
"field1": {
"firstName": "ghi",
"lastName": "jkl"
}
},
"field2": {
"firstName": "ghi",
"lastName": "jkl"
}
}
]
}
This is what I tried:
HTML:
<form id="f1" class="forms">
<div class="f-grp">
<label for ="fn1">First Name</label>
<input type="text" name="fn1" id="fn1" />
</div>
<div class="f-grp">
<label for ="ln1">First Name</label>
<input type="text" name="ln1" id="ln1" />
</div>
</form>
<form id="f2" class="forms">
<div class="f-grp">
<label for ="fn2">First Name</label>
<input type="text" name="fn2" id="fn2" />
</div>
<div class="f-grp">
<label for ="ln2">Last Name</label>
<input type="text" name="ln2" id="ln2" />
</div>
</form>
<button type="submit" id="submit">Submit</button>
JS:
$(document).ready(function(){
$('#submit').click(function(){
setFormObj();
});
});
var setFormObj = function(){
var self = this;
self.myObj = {};
myObj.items = [];
self.tmpObj = {
fieldset: {
field1: {
firstName: "",
lastName: ""
}
},
field2: {
firstName: "",
lastName: ""
}
};
$('.forms').each(function(fKey, fValue){
var _serArr = $(this).serializeArray();
$(_serArr).each(function(sKey, sValue){
var value = sValue.value;
tmpObj.transferOldNumberInfo.addressfields.firstName = value;
});
});
}

Check jquery .serializeArray() function.
It takes an array and creates a set of key/value.
You can check doc here.

Related

Using an AJAX call to asp page then using JSON data returned from page to populate a select box with options

I am trying to populate a select box based on JSON data returned from my ASP page: http://accdbmgr-001-site1.etempurl.com/ajax.asp
This is the data returned from the Server:
{
"data": [{
"Lastname": "Roussel",
"Firstname": "Donald"
}, {
"Lastname": "Sabourin",
"Firstname": "Manon"
}, {
"Lastname": "Kelly",
"Firstname": "Bruce"
}]
}
However, for some reason it just doesn't seem to be able to add my JSON data into the select box. I'd like for the options to appear as: Lastname, FirstName
<div id="test"></div>
<form>
<select id="select1"></select>
</form>
$(document).ready(function() {
$.get('http://accdbmgr-001-site1.etempurl.com/ajax.asp', {
category: 'client',
type: 'premium'
}, function(data) {
alert("success")
//$("#test").html(data)
var obj = JSON.parse(data);
for (i in obj) {
$('#select1').append(new Option(obj[i].Firstname, obj[i].Lastname));
}
});
});
The main issue is because you're looping through obj, when you instead need to loop through the obj.data array.
Also note that you can use map() to build an array of strings which you can then append() once to make the logic more succinct and more performant.
Finally your code is currently creating an option element with Firstname as the text of the element, and Lastname as the value. If you want the text to be in Lastname, Firstname format you need to set the text to that explicitly. Try this:
var obj = {
"data": [{
"Lastname": "Roussel",
"Firstname": "Donald"
}, {
"Lastname": "Sabourin",
"Firstname": "Manon"
}, {
"Lastname": "Kelly",
"Firstname": "Bruce"
}]
}
var options = obj.data.map(function(item) {
return `<option>${item.Lastname}, ${item.Firstname}</option>`;
});
$('#select1').append(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"></div>
<form>
<select id="select1"></select>
</form>
Also note that JSON.parse() is not needed if you set dataType: 'json' on the request, or use $.getJSON()

use html onclick submit button, to search js array and then display specific data back in the original html div

have being watching youtube videos trying to learn how to search array for specific entry data?
here below is a js array example using console.log
Js array example:
var data = {
username: "john",
email: "28#GSDF.COM",
status: true,
id: 25
};
var data = {
username: "jIM",
email: "27#GSDF.COM",
status: false,
id: 23
};
var data = {
username: "Jane",
email: "25#GSDF.COM",
status: false,
id: 22
};
{
console.log(data);
}
here below is html which I want to make it show specific result from above js array with onclick submit button to search array? and then display/print back in the html div.
<html>
<head>
<title>get value</title>
<script type="text/javascript">
function getDisplay(){
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
document.getElementById("display").innerHTML = "username" + username + "<br/>email" + email;
}
</script>
</head>
<body>
<div id="whole">
Username : <input type="text" name="username" id="username">
Email : <input type="email" name="email" id="email"></br>
<button onclick=getDisplay()>Submit</button>
</div>
<div id="display">
</div>
</body>
</html>
if you can recommend any videos or things to read to help me learn would be greatly appreciated.
Firstly what you do is not an array, you want this array-object like this:
var data=[{
username: "john",
email: "28#GSDF.COM",
status: true ,
id: 25
},
{
username: "jIM",
email: "27#GSDF.COM",
status: false,
id: 23
}];
As you can see this is an array with obejcts, now you can work with it.
Use Object.keys(data).
Assuming your json should be like this. and your search logic will look like this.
var data = [
{
username: "john",
email: "28#GSDF.COM",
status: true,
id: 25
},
{
username: "jIM",
email: "27#GSDF.COM",
status: false,
id: 23
},
{
username: "Jane",
email: "25#GSDF.COM",
status: false,
id: 22
}
];
function getDisplay(){
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
data.forEach(function(item, index){
if((item.username == username) && (item.email == email)) {
var displayData = "<li><b>User Name</b>: "+ item.username +"</li>"+
"<li><b>EMail</b>: "+ item.email +"</li>"+
"<li><b>Status</b>: "+ item.status +"</li>"+
"<li><b>ID</b>: "+ item.id +"</li>";
$("#display").html(displayData);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="whole">
Username : <input type="text" name="username" id="username"></br>
Email : <input type="email" name="email" id="email"></br>
<button onclick=getDisplay()>Submit</button>
</div>
<div id="display"></div>
An array of objects should look like this:
var arr = [{
username: "john",
email: "28#GSDF.COM",
status: true,
id: 25
},
{
username: "jIM",
email: "27#GSDF.COM",
status: false,
id: 23
},
{
username: "Jane",
email: "25#GSDF.COM",
status: false,
id: 22
}
]
And in your code you want to do the following :
<html>
<head>
<title>get value</title>
<script type="text/javascript">
var arr = [/*Your data here */];
function getDisplay(){
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
document.getElementById("display").innerHTML = "username" + username + "<br/>email" + email;
for(let i = 0; i < arr.length; i++) {
let element = arr[i];
//Your search logic goes here
}
}
</script>
</head>
<body>
<div id="whole">
Username : <input type="text" name="username" id="username">
Email : <input type="email" name="email" id="email"></br>
<button onclick=getDisplay()>Submit</button>
</div>
<div id="display">
</div>
</body>
</html>

use javascript to push into javascript "members" object

I am trying to push data into a "members" object. This addition doesn't have to be permanent! But my code string doesn't work, although it looks (to me) like it should work fine. Can anyone please tell me why the push below doesn't work?
<script>
var members = [
{ "Class": "B", "Rating": "1776", "ID": "12537964", "Name": "Smith, John", "Expires": "2018.10.18" },
{ "Class": "C", "Rating": "1500", "ID": "12210580", "Name": "Jones, Jim", "Expires": "2019.01.12" },
{ "Class": "B", "Rating": "1759", "ID": "10117780", "Name": "Williams, Paula", "Expires": "2018.09.12" }
]
</script>
HTML:
<form action="" id = "newMember" class="pure-form" method = "">
<fieldset>
<label for="mem-name">Last, First name:</label> <input type="text" id = "mem-name" />
<label for="mem-expires">Membership:</label> <input type="text" id = "mem-expires" /> <br />
<label for="mem-rating">Rating:</label> <input type="text" id = "mem-rating" />
<label for="mem-ID">ID:</label> <input type="text" id = "mem-ID" />
<label for="mem-class">Class:</label> <input type="text" id = "mem-class" />
<button type="button" id="addPlayer" style="margin-left:2rem;" onclick="validateForm()">add new player</button>
<button type="reset">reset form</button>
</fieldset>
</form>
JAVASCRIPT:
<script>
function validateForm() {
var memName = document.getElementById('mem-name').value;
var memExpires = document.getElementById('mem-expires').value;
var memRating = document.getElementById('mem-rating').value;
var memID = document.getElementById('mem-ID').value;
var memClass = document.getElementById('mem-class').value;
if (memName == "") {
alert("Name must be filled out");
return false;
}
//The line below doesn't work:
members.push({Name: "memName", Expires: "memExpires", Rating: "memRating", ID: "memID", Class: "memClass"});
}
</script>
You're pushing the strings, but you've to use variables instead. Instead of this:
members.push({Name: "memName", Expires: "memExpires", Rating: "memRating", ID: "memID", Class: "memClass"});
do this:
members.push({Name: memName, Expires: memExpires, Rating: memRating, ID: memID, Class: memClass});
For example "memName" is a string which has memName in it, whereas if you want the value of the text input, which you're storing in a variable named memName, you need to unwrap the value from double quotes.

angularjs: ng-model double object

I try to achieve a double nested object. (Example Below)
The Problem is that my current Code is generating a Array inside a Object.
<div ng-if="newResultUnits()" ng-repeat="set in sets" ng-model="newexercise.sets[$index]">
<label>Set {{$index+1}}</label>
<label>
<label>
<input type="text" ng-repeat="resultUnit in newResultUnits()" ng-model="newexercise.sets[$parent.$index][$index].value" placeholder="{{resultUnit.name}}">
</label>
</label>
</div>
Example (the name attr is added later):
{
name:"MultiTest",
sets:[
{
0:{
value:"10",
name:"Kg"
},
1:{
value:"10",
name:"Wdh"
}
}
]
}
This is how it should be: (Please note the doubble [[ and the missing 0:)
{
"name": "MultiTest",
"sets": [
[
{
"value": "10",
"name": "Kg"
},
{
"value": "10",
"name": "Wdh"
}
]
]
}
Im sorry if I mixedup Array and Object.. Thanks!
You need properly initialize your data structures. So in controller begin with
$scope.newexercise = { sets: [] };
So Angular knows that you want $scope.newexercise to be an array. Then in template use ngInit on every inner loop ng-init="newexercise.sets[$parent.$index] = []":
<div ng-repeat="set in sets">
<label>Set {{$index+1}}</label>
<label>
<label>
<input type="text"
ng-repeat="resultUnit in newResultUnits()"
ng-init="newexercise.sets[$parent.$index] = []"
ng-model="newexercise.sets[$parent.$index][$index].value"
placeholder="{{resultUnit.name}}">
</label>
</label>
</div>
Demo: http://plnkr.co/edit/s1rInT8rLg50ISsSVxyV?p=preview

Angular UI typeahead startswith

I have a problem with typeahead. I have a field with name and surname of a person, If I type A I would like to see the focus on the surname and not on the leading character that is the name.
this is an example:
function TypeaheadCtrl($scope) {
$scope.selected = undefined;
$scope.Person = ['Jane Smith', 'John Smith', 'Sam Smith', 'John Doe','Daniel Doe'];
}
When I type S i Would like to see only jane smith and john smith. There's a way to do this??
plunker: http://plnkr.co/edit/inwmqYCCRsjs1G91Sa3Q?p=preview
I assume you would want each of the listed items found in the sourceArray to have the search term highlighted only for the surname. That is not possible without modifying the directive itself, but I have an alternate solution that, although it also highlights the search term in the first name (if matched), ONLY presents results for persons with a surname matched by the search term. I hope this helps:
angular.module("firstChar", ["ui.bootstrap"]);
angular.module("firstChar").controller("TypeaheadCtrl", function($scope, $filter) {
$scope.selected = undefined;
// ==========================================================
// You would have to replace the JSON assignment code below
// with a call to $http.get, to get that file you talked
// about in your comment below:
//
// $http.get('OutAnagrafica.json').success(function (data) {
// $scope.OutAnagrafica = data;
// });
//
// ==========================================================
$scope.OutAnagrafica = [
{
"Name": "Jane Smith"
},
{
"Name": "John Smith"
},
{
"Name": "Sam Smith"
},
{
"Name": "Sam Northrop"
},
{
"Name": "John Doe"
},
{
"Name": "Daniel Doe"
}
];
$scope.persons = $scope.OutAnagrafica.map(function (person) {
var nameParts = person.Name.split(" "),
name = nameParts[0],
surname = nameParts.slice(1).join(" ");
return {
"name": name,
"surname": surname
};
});
$scope.getPersonsFromSurnames = function(searchTerm) {
return $filter("filter")($scope.persons.map(function (person) {
return {
"fullname": person.name + " " + person.surname,
"surname": person.surname
};
}), {
"surname": searchTerm
});
}
});
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.11.0/ui-bootstrap-tpls.min.js"></script>
<div ng-app="firstChar">
<div class="container-fluid" ng-controller="TypeaheadCtrl">
<div>Selected: <span>{{selected}}</span>
</div>
<div>
<input type="text" ng-model="selected" typeahead="person.fullname for person in getPersonsFromSurnames($viewValue)">
</div>
</div>
</div>
From http://angular-ui.github.io/bootstrap/#/typeahead,
looking at this particular line
<input type="text" ng-model="asyncSelected" placeholder="Locations loaded via $http" typeahead="address for address in getLocation($viewValue)" typeahead-loading="loadingLocations" class="form-control">
You can probably do something like
<input type="text" ng-model="selected" typeahead="name for name in getPersonLastName($viewValue)">
Meaning that you have a getPersonLastName function that looks into $scope.Person and returns names that matches the surname with the $viewValue.

Categories