Push and select data from Array of Objects - javascript

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>

Related

Jquery append method returning html tags instead of the proper formats

The feature is for a quiz and im retrieving the data for the quiz that is the questions and answers and appending it to my div having id test_box. The data has been successfully retrieved but instead of proper formatting the data, it is returning me in form of html tags.
Here is my code snippet:
const url = window.location.href
const testBox = document.getElementById('test_box')
$.ajax({
type: 'GET',
url: `${url}/data`,
success: function(response){
const data = response.data
data.forEach(element => {
for (const [question, answers] of Object.entries(element)){
testBox.append(`
<div class="question_box">
<div>
<b>${question}</b>
</div>
`);
answers.forEach(answer => {
testBox.append(`
<div>
<input type="radio" class="ans" id=${question}-${answer}" name="${question}"
value="${answer}">
<label for="${question}">${answer}</label>
</div>
`)
})
testBox.append(`</div>`);
}
});
},
error: function(error){
console.log(error)
}
});
output of response.data
Array(2)0: {1000-100 = ?: Array(4)}1: {1 + 1 = ?: Array(4)}length:
2__proto__:
Array(0)
You can first append your outer div i.e : question_box inside your dom and then to append option inside your question_box you can use $("#test_box .question_box:last") this will target last question_box added and will append options there .
Demo Code :
//just for demo..
var data = [{
"1000 - 100 = ?": ["a", "v", "c", "d"]
}, {
" 1 + 1 = ?": ["a", "v", "c", "d"]
}]
data.forEach(element => {
for (const [question, answers] of Object.entries(element)) {
//use it like this..
$("#test_box").append(`
<div class="question_box">
<div>
<b>${question}</b>
</div>
</div>`);
answers.forEach(answer => {
//now to append inside question_box use :last
$("#test_box .question_box:last").append(`
<div>
<input type="radio" class="ans" id=${question}-${answer}" name="${question}"
value="${answer}">
<label for="${question}">${answer}</label>
</div>
`)
})
}
});
.question_box {
border: 1px solid
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test_box"></div>

Uncaught TypeError: renderIncomes.overIncome is not a function at HTMLInputElement.<anonymous>

I'm currently learning Javascript at school, so my codes may look like a beginner coding style.
I wanted my list(arrays) on the browser to change when I check the checkbox input. But, when I do check the checkbox, it will say this, "Uncaught TypeError: renderIncomes.overIncome is not a function at HTMLInputElement."
In my html file, I set up the input as a checkbox type. And in my javascript file, I added an eventlistener to change when I check the checkbox. The list on the browser should only change when the income is greater than 300. Here are the codes to both html and javascript files.
let user = {
firstName: 'Zoraida',
lastName: 'Rodriguez',
accountType: 'Personal'
}
let renderUser = {
renderName: function() {
const h1 = document.createElement('h1')
h1.textContent = `Welcome ${user.firstName}!`
document.querySelector('#user').appendChild(h1)
}
}
renderUser.renderName()
let incomes = [{
type: 'monthly wages',
date: '09/01/2018',
income: 900,
}, {
type: 'yardwork',
date: '09/07/2018',
income: 100,
}, {
type: 'eBay',
date: '09/14/2018',
income: 250,
}]
let renderIncomes = {
renderList: function() {
document.querySelector('#incomes').innerHTML = ''
const h3 = document.createElement('h3')
h3.textContent = `You have a list of ${incomes.length} incomes.`
document.querySelector('#incomes').appendChild(h3)
incomes.forEach(function(each) {
const p = document.createElement('p')
p.textContent = `On ${each.date}, you received $${each.income} from ${each.type}.`
document.querySelector('#incomes').appendChild(p)
})
},
totalIncome: function() {
document.querySelector('#totalIncome').innerHTML = ''
let totalIncome = 0
incomes.forEach(function(income) {
totalIncome += income.income
})
const h2 = document.createElement('h2')
h2.textContent = `Total income: $${totalIncome}`
document.querySelector('#totalIncome').appendChild(h2)
},
overIncome: function() {
incomes.filter(function(incomeResults) {
return incomeResults.income > 300
})
}
}
renderIncomes.renderList()
renderIncomes.totalIncome()
renderIncomes.overIncome()
document.querySelector('#new-incomes').addEventListener('submit', function(e) {
e.preventDefault()
incomes.push({
type: e.target.elements.typeOfIncome.value,
date: e.target.elements.date.value,
income: parseInt(e.target.elements.income.value)
})
renderIncomes.renderList()
renderIncomes.totalIncome()
e.target.elements.typeOfIncome.value = ''
e.target.elements.date.value = ''
e.target.elements.income.value = ''
})
document.querySelector('#filterincomes').addEventListener('change', function(e) {
renderIncomes.overIncome = e.target.checked
renderIncomes.overIncome()
})
<body>
<div id="user" class="center"></div>
<hr>
<br>
<div id="totalIncome" class="center"></div>
<div id="incomes" class="center"></div>
<form id="new-incomes" class="center">
<label>
Date: <input type="text" placeholder="MM/DD/YYYY" name="date">
</label>
<label>
Type: <input type="text" placeholder="From Where" name="typeOfIncome">
</label>
<label>
Income: <input type="text" placeholder="Type New Income" name="income">
</label>
<button>Submit</button>
</form>
<label>
<input id="filterincomes" type="checkbox">Check here for incomes over $300
</label>
<script src="test.js"></script>
</body>
you are assigning property overIncome of object renderIncomes to boolean value
so there is no function overIncome() after line
renderIncomes.overIncome = e.target.checked
remove the line, your code will work fine
In your addEventListener you are assigning a value to a object
Change the below code as commend and please note below solution will fix your Uncaught TypeError error
document.querySelector('#filterincomes').addEventListener('change', function(e) {
//renderIncomes.overIncome = e.target.checked
renderIncomes.overIncome()
})

How to make json array and object using checkbox in formfields

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>

Angular: Showing only checked items in a checkbox list

Is it possible to show only a list of checked items in a checkbox list?
What I want to do is select a few items on a checked list and when I press "Show only checked items", I want to toggle between showing only the checked items in the checkbox list and showing the entire list with the checked items.
I searched angular's site but wasn't able to find a solution to it.
Fiddle: http://jsfiddle.net/fjoLy5sq/422/
<div ng-controller="DemoCtrl">
<label ng-repeat="role in roles">
<input type="checkbox" checklist-model="user.roles" checklist-value="role.id"> {{role.text}}
</label>
<br>
<button ng-click="checkAll()">check all</button>
<button ng-click="uncheckAll()">uncheck all</button>
<button ng-click="checkFirst()">check first</button>
<button ng-click="checkFirst()">Show only Checked</button>
<br><br>
user.roles {{ user.roles | json }}
</div>
Javascript:
angular.module("DemoApp", ["checklist-model"])
.controller('DemoCtrl', function($scope) {
$scope.roles = [
{id: 1, text: 'guest'},
{id: 2, text: 'user'},
{id: 3, text: 'customer'},
{id: 4, text: 'admin'}
];
$scope.user = {
roles: [2, 4]
};
$scope.checkAll = function() {
$scope.user.roles = $scope.roles.map(function(item) { return item.id; });
};
$scope.uncheckAll = function() {
$scope.user.roles = [];
};
$scope.checkFirst = function() {
$scope.user.roles.splice(0, $scope.user.roles.length);
$scope.user.roles.push(1);
};
});
Add a new variable in controller:
$scope.showAll = true;
In a view inverse the value of showAll when Show only Checked button is clicked:
<button ng-click="showAll = !showAll">Show only Checked</button>
To show only checked items, use Array.includes method, and check that current role is in user.roles:
<label ng-repeat="role in roles" ng-if="user.roles.includes(role.id)">
<input type="checkbox" checklist-model="user.roles" checklist-value="role.id"> {{role.text}}
</label>
Working demo

Display radio button data from array value in scope angular

I have web service call. I am getting response from webservice like this :
var SSOUserResponse = [
{
"UserName": "se",
"FirstAndLastName": "Sam ",
"EmailAddress": "segfgf#x.net"
},
{
"UserName": "se2",
"FirstAndLastName": "Joe ", //
"EmailAddress": "se266#gmail.com" //
}
];
or
SSOUserResponse array length can me more also.
$scope.launchArray = [];
I want to display this data in my templete.
What I am doing :
if (SSOUserResponse.length > 1) {
var launchArrayVal = [];
for (var i = 0; i < SSOUserResponse.length;i++){
launchArrayVal.push(
{ name: SSOUserResponse[i].UserName, email: SSOUserResponse[i].EmailAddress }
);
$scope.launchArray = launchArrayVal;
}
}
I have a templete :
<div class="modal-body">
<div>Please select an one data</div>
<div>
<input type="radio" ng-model="launchArray" name="group1" value="{{launchArray.name}}">
</div>
</div>
I want to display radio button with with username and email to display..
I tried ng-repeat also. It is not working.
Can u guide me what I doing wrong or what I can do?
Checkout this
<div class="modal-body">
<div>Please select an one data</div>
<div ng-repeat = 'item in launchArray'>
<input type="radio" ng-model="selected.value" name="group" ng-value="item.name">
<div> Name : {{item.name}}</div>
<div> Email : {{item.email}}</div>
</div>
</div>
<br>
<br>
<br>
<br>
<div >
<b>Selected Value :: </b>{{selected.value}}
</div>
var SSOUserResponse = [
{
"UserName": "se",
"FirstAndLastName": "Sam ",
"EmailAddress": "segfgf#x.net"
},
{
"UserName": "se2",
"FirstAndLastName": "Joe ", //
"EmailAddress": "se266#gmail.com" //
}
];
if (SSOUserResponse.length > 1) {
var launchArrayVal = [];
for (var i = 0; i < SSOUserResponse.length;i++){
launchArrayVal.push(
{ name: SSOUserResponse[i].UserName, email: SSOUserResponse[i].EmailAddress }
);
}
$scope.launchArray = launchArrayVal;
$scope.selected = {value: null};
}
You want to show one radio button per result, right?
This is when you would use ng-repeat. You didn't mention what the problem was when you used ng-repeat.
Currently, in your template, you're doing {{launchArray.name}} which won't work, since launchArray is an array... it doesn't have a name property.
Using ng-repeat, you loop over each item in launchArray and render a radio button each time:
<div class="modal-body">
<div>Please select an one data</div>
<div ng-repeat="item in launchArray">
<input type="radio" name="group1" value="{{item.name}}">
<span>{{item.name}} ({{item.email}})</span>
</div>
</div>

Categories

Resources