How to make json array and object using checkbox in formfields - javascript

Here i have one form and one form fields , that is checkbox,after checking the the three fields i want to make JSON format , but i am not able do this,if anyone one know please update my answer.
function rentfunction(){
var arr1 = [];
$.each($("input[name='furniture_check']:checked"),function(){
var furniture = $(this).val();
arr1.push(furniture);
});
var data = {
"rentProperty" :{
"furnitureType" :arr1,
}
}
console.log(data);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="furniture_check" value="Ward robe">Ward robe <br>
<input type="checkbox" name="furniture_check" value="Lights">Lights <br>
<input type="checkbox" name="furniture_check" value="Fan">Fan <br>
<input type="checkbox" name="furniture_check" value="Fridge">Fridge <br><br><br>
<button type="button" id="rentBtnSubmit" onclick="rentfunction()">Submit</button>
</form>
expected answer
suppose i am clicking Ward robe & Lights & Fridge and i am clicking the submit button means i want to make json like this
{
"rentProperty":
{
"fullName" : "Some Name"
},
"floorType": [
{
"floorTypeName": "Ward robe"
},
{
"floorTypeName" :"Lights"
},
{
"floorTypeName" :"Fridge"
}
]
}
I am also tried but i am not able to make expected JSON format,i am getting results like this
{
"rentProperty": {
"furnitureType": [
"Ward robe",
"Lights",
"Fan"
]
}
}

here is the modified code for your desired output:
function rentfunction(){
var arr1 = [];
var data={
"rentProperty": {
"fullName" : "Some Name"
},
"floorType":[]
};
$.each($("input[name='furniture_check']:checked"),function(){
var furniture = $(this).val();
arr1.push({"floorTypeName": furniture });
});
data.floorType=arr1;
//or data["floorType"]=arr1;
console.log(data);
}

Here is how you could get your desired output:
$('#rentBtnSubmit').click(function () {
var data = {
rentProperty: {
name: "some name"
},
floorType: $.map($("input[name=furniture_check]:checked"), function(chkbox){
return { floorTypeName: $(chkbox).val() };
})
};
console.log(data);
return false; // if you need to cancel submission.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="furniture_check" value="Ward robe">Ward robe <br>
<input type="checkbox" name="furniture_check" value="Lights">Lights <br>
<input type="checkbox" name="furniture_check" value="Fan">Fan <br>
<input type="checkbox" name="furniture_check" value="Fridge">Fridge <br><br><br>
<button type="button" id="rentBtnSubmit">Submit</button>
</form>

Related

Push and select data from Array of Objects

So I have an Array of object like this :
var dataQuestions = [ {
question : 1,
reponse : 3,
},{
question : 2,
reponse : 7,
},{
question : 3,
reponse : 5,
}];
I want to add data in this array by clicking on a button (onclick action)
And the other button get the number of the reponse (ex: onclick(2) responce->7)
besides lack of info provided , this might help you build your own
var dataQuestions = [ {
question : 1,
response : 3,
},{
question : 2,
response : 7,
},{
question : 3,
response : 5,
}];
function addQ(){
var question = parseInt(document.getElementById("question").value);
var response = parseInt(document.getElementById("response").value);
dataQuestions.push(
{
question: question,
response : response
}
)
console.log(dataQuestions);
}
function getResp(){
var getResp = parseInt(document.getElementById("getresponse").value);
var res = dataQuestions.find(q=>q.question===getResp);
console.log(res.response)
}
<label for="question">Question:</label>
<input type="text" id="question" ><br><br>
<label for="response">Reponse:</label>
<input type="text" id="response" >
<button onclick="addQ()">Add</button>
<br>
<br>
<label for="getresponse">Get Response of:</label>
<input type="text" id="getresponse" >
<button onclick="getResp()">Get</button>
You should ass your tries to the question.
Anyway, this is a simple solution that does what you asked:
let responses = []
document.getElementById("collect").addEventListener("click", () => {
responses = [];
for(let el of document.getElementsByClassName("answer")){
responses.push({
question: el.id,
answer: el.value
});
}
});
document.getElementById("show").addEventListener("click", () => {
const placeHolder = document.getElementById("answer_list");
placeHolder.innerHTML = "";
responses.forEach((r) => {
placeHolder.innerHTML += `Question: ${r.question} Answer ${r.answer} <br>`;
});
});
<div>
question 1: <input id="1" class="answer"/><br>
question 2: <input id="2" class="answer"/><br>
question 3: <input id="3" class="answer"/>
</div>
<div>
<button id="collect">Collect answers</button>
<button id="show">Show answers</button>
</div>
<div id="answer_list">
</div>

Highlight moved item from one listbox to other listbox in angularjs

There are two listbox, We need move to list items between the box.
Moving the item from one to other isn't the question.
This is already posted in the question
AngularJS moving items between two select list
Here is the plunker link http://plnkr.co/edit/RYEmpkBjQStoCfgpWPEK?p=preview for moving one list item in other
The question/problem is how to highlight the moved item from one list item to other list item
<label for="aclients">Available Clients</label>
<select size="5" multiple ng-model="available" ng-options="client as client.name for client in availableclients" style="width: 400px"></select>
<input id="moveright" type="button" value="Add Client" ng-click="moveItem(available[0], availableclients,selectedclients)" />
<input id="moverightall" type="button" value="Add All Clients" ng-click="moveAll(availableclients,selectedclients)" />
<input id="move left" type="button" value="Remove Client" ng-click="moveItem(selected[0], selectedclients,availableclients)" />
<input id="moveleftall" type="button" value="Remove All Clients" ng-click="moveAll(selectedclients,availableclients)" />
<label for="sclients">Selected Clients</label>
Script
angular.module('app', []).controller('MoveCtrl', function($scope) {
$scope.moveItem = function(item, from, to) {
console.log('Move item Item: '+item+' From:: '+from+' To:: '+to);
//Here from is returned as blank and to as undefined
var idx=from.indexOf(item);
if (idx != -1) {
from.splice(idx, 1);
to.push(item);
}
};
$scope.moveAll = function(from, to) {
console.log('Move all From:: '+from+' To:: '+to);
//Here from is returned as blank and to as undefined
angular.forEach(from, function(item) {
to.push(item);
});
from.length = 0;
};
$scope.selectedclients = [];
$scope.availableclients = [
{
id: 1,
name: 'foo'
},
{
id: 2,
name: 'bar'
},
{
id: 3,
name: 'baz'
}
];
});
Early replies are appreciated.

Check if zip code in input exists in JSON and get category

I have a JSON element with a bunch of different zip codes associated with "zones." What I would like to do is allow a user to submit their zip code, check if the zip code exists within the JSON element and then report which "zone" it belongs to if it does:
var zones = [{
"zone": "one",
"zipcodes": ["69122", "69125", "69128", "69129"]
},
{
"zone": "two",
"zipcodes": ["67515", "67516", "67518", "67521"]
}
];
$(function() {
$('#userZip').submit(function(e) {
e.preventDefault();
var userZip = $('input[type="text"]').val();
// Check if zip exists in JSON and report which zone it belongs to
});
});
i {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="userZip">
<i>Enter zip code "69122" as an example</i>
<input type="text" placeholder="zip" />
<input type="submit" />
</form>
You can use Array.find
var zones = [
{
"zone": "one",
"zipcodes": ["69122", "69125", "69128","69129"]
},
{
"zone": "two",
"zipcodes": ["67515", "67516", "67518", "67521"]
}
];
$(function() {
$('#userZip').submit(function(e) {
e.preventDefault();
var userZip = $('input[type="text"]').val();
// find the first zone with the userZip inside its zipcodes list
var zone = zones.find(function(zone) {
return zone.zipcodes.indexOf(userZip) > -1;
});
alert("Zone: " + zone.zone);
});
});
i {
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="userZip">
<i>Enter zip code "69122" as an example</i>
<input type="text" placeholder="zip" />
<input type="submit" />
</form>

AngularJS custom filter with checkbox and radio button

My application has to dynamically list file items using a Radio button, Checkbox and AngularJS custom filter (code given below).
I have tried few options, but could not get the working code.
I have created the fiddle link and find the same below:
https://jsfiddle.net/38m1510d/6/
Could you please help me to complete the below code to list the file items dynamically ?
Thank you.
<div ng-app="myApp" ng-controller="myCtrl">
<label>
<input type="radio" ng-model="inputCreatedBy" value="byX"
ng-click="myFilter(?, ?)"> by X
<input type="radio" ng-model="inputCreatedBy" value="byAll"
ng-click="myFilter(?, ?)"> by All
</label> <br/><br/>
<label>
<input type='checkbox' ng-model='Type1Files' ng-change='myFilter(?, ?)'>Type1 files
<input type='checkbox' ng-model='Type2Files' ng-change='myFilter(?, ?)'>Type2 files
</label>
<br/><br/>
<label ng-repeat="file in displayFiles | filter: myFilter(createdBy, fileType)">
{{ file.name }}
</label>
</div>
</body>
<script>
var app = angular.module("myApp",[]);
app.controller('myCtrl', function ($scope) {
$scope.files = [
{ name: 'file1', type:'Type1', createdBy: 'X' },
{ name: 'file2', type:'Type2', createdBy: 'X' },
{ name: 'file3', type:'Type2', createdBy: 'Y' },
{ name: 'file4', type:'Type1', createdBy: 'Y' }
];
$scope.displayFiles = [];
$scope.myFilter = function() {
return new function(createdBy, fileType) {
var displayFilesTemp = [];
for(i=0;i<$scope.files.length;i++) {
if($scope.files[i].type ==fileType && $scope.files[i].createdBy == createdBy && !checkArrayContainsObject(displayFilesTemp, displayFiles[i])) {
displayFilesTemp.push(displayFiles[i]);
}
}
return displayFilesTemp;
};
};
});
function checkArrayContainsObject(a, obj) {
for (var i = 0; i < a.length; i++) {
if (JSON.stringify(a[i]) == JSON.stringify(obj)) {
return true;
}
}
return false;
}
</script>
Here's a working fiddle - http://jsfiddle.net/1gfaocLb/
Radio is a unique value, so it's easy to filter by.
Selected types are array of values so it's needs a little more attention.
myApp.filter('typesFilter', function() {
return function(files, types) {
return files.filter(function(file) {
if(types.indexOf(file.type) > -1){
return true;
}else{
return false;
}
});
};
});
According the shared code / fiddle, I've simplified the code for a possible solution. The file filtering logic is not foreseen since it was not clear what needed to be done exact.
<body ng-app="myapp">
<div ng-controller="myctrl">
<label>
<input type="radio" ng-model="inputCreatedBy" value="byX"
ng-click="filterFiles()"> by X
<input type="radio" ng-model="inputCreatedBy" value="byAll"
ng-click="filterFiles()"> by All
</label> <br/><br/>
<label>
<input type='checkbox' ng-model='Type1Files' ng-change='filterFiles()'>Type1 files
<input type='checkbox' ng-model='Type2Files' ng-change='filterFiles()'>Type2 files
</label>
<br/><br/>
<label ng-repeat="file in filteredFiles">
{{ file.name }} <br/>
</label>
</div>
</body>
var app = angular.module("myapp",[])
app.controller('myctrl', function ($scope) {
$scope.files = [
{ name: 'file1', type:'Type1', createdBy: 'X' },
{ name: 'file2', type:'Type2', createdBy: 'X' },
{ name: 'file3', type:'Type2', createdBy: 'Y' },
{ name: 'file4', type:'Type1', createdBy: 'Y' }
];
$scope.filterFiles = function(){
// init dict
var files = [];
// loop & check files
angular.forEach($scope.files, function(value, key) {
// do file check and push to files.push when matching with criteria
files.push(value);
});
// set scope files
$scope.filteredFiles = files;
}
// init filter on ctrl load
$scope.filterFiles();
});
First, you don't have to use any directive as ng-if/ng-click to achieve what you want. Just changing how the values are binding into the radio button and checkbox can do the trick. Also you just need to do a custom filter to handle the checkbox selections, since radio button is unique. Take a look on my solution:
angular.module("myApp", [])
.controller('myCtrl', function($scope) {
$scope.files = [
{
"name":"file1",
"type":"Type1",
"createdBy":"X"
},
{
"name":"file2",
"type":"Type2",
"createdBy":"X"
},
{
"name":"file3",
"type":"Type2",
"createdBy":"Y"
},
{
"name":"file4",
"type":"Type1",
"createdBy":"Y"
}
];
})
.filter('typesFilter', function() {
return function(files, types) {
if (!types || (!types['Type1'] && !types['Type2'])) {
return files;
}
return files.filter(function(file) {
return types['Type1'] && file.type == 'Type1' || types['Type2'] && file.type == 'Type2';
});
};
});
<html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="myCtrl">
<form action="" name="form">
Created by:
<input type="radio" id="radio1" ng-model="criteria.createdBy" value="X">
<label for="radio1">by X</label>
<input type="radio" id="radio2" ng-model="criteria.createdBy" value="">
<label for="radio2">by All</label>
<br/>
<br/>
Type:
<input type="checkbox" id="check1" ng-model="criteria.type['Type1']">
<label for="check1">Type1 files</label>
<input type="checkbox" id="check2" ng-model="criteria.type['Type2']">
<label for="check2">Type2 files</label>
</form>
<pre ng-bind="criteria | json"></pre>
<div ng-repeat="file in files | filter: { createdBy: criteria.createdBy } | typesFilter: criteria.type" ng-bind="file.name"></div>
</body>
</html>

KnockoutJS not binding

I cant seem to get the binding to work on my KnockoutJS app.
JSFIDDLE -> http://jsfiddle.net/maylortaylor/pfqnkj17/
Here is the format of my JSON (generated by using <pre data-bind="text: ko.toJSON($root.forms,null,2)"></pre>)
[
{
"formTitle": "formTitle",
"formDescription": "formDesc",
"fieldTemplates": [
{
"fieldId": "text1",
"title": "title",
"description": "description fieldTemplate",
"isReq": true
},
{
"fieldId": "text2",
"title": "ttitle22",
"description": "description fieldTemplate 2",
"isReq": false
}
]
}
]
And here is how i am trying to call it in the page
<div id="MiddleColumn">
<input data-bind="textInput: $root.formTitle" type="text" placeholder="Title" class="span8 hideOffFocus input-full large-type">
<input data-bind="textInput: formDescription" type="text" placeholder="Description" class="hideOffFocus input-full">
</div
neither of those bindings work.
I create the forms object here
var FormModel = function (forms) {
var self = this;
self.forms = ko.observableArray(ko.utils.arrayMap(forms, function (form) {
return {
formTitle: form.formTitle, formDescription: form.formDescription,
fieldTemplates: ko.observableArray(form.fieldTemplates) };
}));
};
ko.applyBindings(new FormModel(initialData));
i hope your are expecting something like this
Working fiddle here
Now if you change something in textboxes in preview you can see automatic updates i.e mapping does make things back to ko way .
View Model :
var mapping = {
'fieldTemplates': {
create: function (options) {
return new FormModel(options.data);
}
}
}
function FormModel(forms) {
var self = this;
self.forms = ko.observableArray();
ko.mapping.fromJS(forms, mapping, self);
// other stuff
}
View :
<div id="MiddleColumn">
<input data-bind="textInput: $root.formTitle" type="text" />
<input data-bind="textInput: $root.formDescription" type="text"/><br/>
<div data-bind="foreach:$root.fieldTemplates">
<span data-bind="text:fieldId"></span>
<span data-bind="text:title"></span>
<span data-bind="text:description"></span>
<span data-bind="text:isReq"></span>
<br/>
</div>
</div>

Categories

Resources