use javascript to push into javascript "members" object - javascript

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.

Related

Get Dynamic Input ID javascript

I have an input type check box and load from database and form like this
<input type="checkbox" name="akses[]"
id="<?php echo $menu_id;?>"
value="<?php echo $action_name;?>"> <?php echo $menu_name;?>
and my json is
{
"status": 200,
"message": "sukses",
"data": {
"fullname": "TEST",
"username": "TEST_USER",
"position": "24",
"privileges_status": "based on jabatan",
"list_menu": [{
"action_name": "menu1 ",
"parent_id": 9,
"menu_id": 15,
"menu_name": "Menu 1"
}, {
"action_name": "menu2",
"parent_id": 9,
"menu_id": 16,
"menu_name": "Menu 2"
}]
}
}
I'm already successfully parsing the id using ajax, but the problem is that I don't know how to to check when id from json is same like the id in input.
If I define manually like
<input type="checkbox" name="akses[]" id="15" value=""> Menu 1
I can check and automatically check the checkbox
Now I change my input type like this
<input type="checkbox" name="akses[]" id="menu1" value=""> Menu 1
UPDATE: The js like this after implementing suggested answer
for (var i = 0; i < res['data']['list_menu'].length; i++)
{
var action_name = res['data']['list_menu'][i]['action_name'];
var idsFromJSON = new Array();
idsFromJSON.push(action_name);
console.log(idsFromJSON);
$("[name='akses[]']").each(function() {
this.checked=idsFromJSON.indexOf(this.id)!=-1;
});
}
but didn't work. if I declare array manually like this it works
var idsFromJSON=["menu1", "menu2"];
You want something like this
I would however recommend not to have numeric IDs
var idsFromJSON=["menu15","menu16"];
$("[name='akses[]']").each(function() {
this.checked=idsFromJSON.indexOf(this.id)!=-1;
});

ngOptions with dynamic option array from index

I am trying to use ngRepeat. Within that, I have a select element whos options vary depending on another select. I currently am calling vm.getOperators(filter.keyIndex) in the ng-options, but I get and indefinite loop error from angular. How can I have the following "filterOperator" select options depend on filterColumn select value within an ngRepeat?
html:
<div class="form-group row" ng-repeat="filter in vm.filters">
<div class="col-sm-4">
<select class="form-control" name="filterColumn" ng-model="filter.keyIndex">
<option ng-repeat="key in vm.filterOptions.keys"
value="{{ $index }}">
{{ key.column }}
</option>
</select>
</div>
<div class="col-sm-2">
<select class="form-control" name="filterOperator" ng-model="filter.operator" ng-options="key as value for (key, value) in vm.getOperators(filter.keyIndex)"></select>
</div>
<div class="col-sm-4" ng-model="filter.value">
<input type="text" class="form-control"/>
</div>
<div class="col-sm-1" ng-show="$last" ng-click="removeFilter($index)">
<button type="button" class="btn btn-primary"><span class="glyphicon glyphicon-plus"></span></button>
</div>
<div class="col-sm-1" ng-show="vm.filters.length > 1" ng-click="addFilter()">
<button type="button" class="btn btn-danger"><span class="glyphicon glyphicon-remove"></span></button>
</div>
</div>
controller.js:
app.controller('searchCtrl', function() {
var defaultFilter = {
keyIndex: "0",
operator: "",
value: "",
};
var operatorMap = {
"0": "=",
"1": "<",
};
var vm = this;
vm.filterOptions = {
"operators": {
"type1": ["0", "3"],
"type2": ["1", "2", "3"]
},
"keys": [
{
"datatype": "type1",
"name": "a",
"column": "col1"
},
{
"datatype": "type1",
"name": "b",
"column": "col2"
},
{
"datatype": "type2",
"name": "c",
"column": "col3"
}
]
};
vm.filters = [];
//vm.removeFilter = removeFilter;
//vm.addFilter = addFilter;
vm.getOperators = getOperators;
function getOperators(keyIndex) {
var operators = [];
var dataType = vm.filterOptions.keys[keyIndex].datatype;
if (vm.filterOptions.operators[dataType]) {
angular.forEach(vm.filterOptions.operators[dataType], function (operator, index) {
var obj = {};
obj[dataType] = (operatorMap[operator] ? operatorMap[operator] : operator);
operators.push(obj);
});
}
return operators;
}
(function init() {
// I am actually getting the filterOptions with a REST call, but I've included the data already
// The following is done after the successful REST call
// add the first filter
var filter = defaultFilter;
filter.operator = Object.keys(getOperators(filter.keyIndex))[0];
vm.filters.push(filter);
}).call();
});
Here's a plunker: https://plnkr.co/edit/yGyvwThuWWnNph72OAT0
Okay, so I figured this out.
First, don't generate an array in the getOperators method. You can return and array that is already defined, but you can't generate a new array here. This leads to an indefinite loop as angular detects a change and call the getOperators method again.
So what I did was...
after the data was fetched from the REST service, I call a function "transformOperators". This implements the looping I was doing in "getOperators" and stores this "transformed data" in a class level object.
in "getOperators" I simply do an object lookup and return the results.

How to pass multiple forms serialized Object to an array Jquery

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.

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

Generate JSON using jQuery

I have 4 inputs in a form:
<form id="mark_date_form">
<input type="text" name="title" class="form-control" placeholder="Title" value="motherday">
<input type="text" name="date" class="form-control datepick" placeholder="MM/DD" value="05/13">
<input type="text" name="title" class="form-control" placeholder="Title" value="fatherday">
<input type="text" name="date" class="form-control datepick " placeholder="MM/DD" value="06/18">
</form>
When I use $('#mark_date_form').serializeArray() in jQuery, it returns
[
{
"name": "title",
"value": "motherday"
},
{
"name": "date",
"value": "05/13"
},
{
"name": "title",
"value": "fatherday"
},
{
"name": "date",
"value": "06/18"
}
]
The question is I have to come out with something like this:
[
{
"title": "motherday",
"date": "05/13"
},
{
"title": "fatherday",
"date": "06/18"
}
]
What should be the jQuery looks like?
Thank you very much!
I think you are looking for this $("#mark_date_form").serialize();
Update: sorry for the #daniel-cai is correct.
Use $("#mark_date_form").serializeArray(); for getting JavaScript literal object.
You can use this:
var a = [];
$('#mark_date_form input').each(function(){
if($(this).attr('name')=='title'){
a.push({"title":$(this).val(),"date":$(this).next().val()});
}
});
console.log(a);
Output:
[Object { title="motherday", date="05/13"}, Object { title="fatherday", date="06/18"}]
Simple way to get a json file as you want is:
var o = {};
$("#mark_date_form").serializeArray().map(function(x){o[x.name] = x.value;});
console.log(o);
Result:
Object {title: "motherday", date: "05/13"}
DEMO: http://jsfiddle.net/gon250/s3xerkgc/1/
Hope it's helps.

Categories