I am generating form dynamically, on textbox, I am binding calculateBCT function like below
<input matInput type="text" (keyup)="calculateBCT($event)" formControlName="avgBCT"> and returning result on below textbox with ngModel.
<input matInput type="text" [(ngModel)]="calculatedResult" formControlName="avgCapacity">.
Expected output - If i will enter value in Textbox0, it will call calculateBCT function and reflect result in Result0 textbox only, When i will enter value in Textbox1 it will call calculateBCT function and reflect result in Result1 textbox likewise..
Can anyone help me to get expected output
Here i have created stackblitz demo with code
Try this, and see if it helps.
In app.component.html, make below changes:
Remove [(ngModel)]="calculatedResult" as you are already using formControlName
Pass index i to calculateBCT as (keyup)="calculateBCT($event, i)"
In app.component.ts, modify the calculateBCT method as:
calculateBCT($event, index: number) {
// Your existing logic goes here...
const calculatedResult = result ? result : 0;
// In below code, please put some checks to ensure that formControl does exist
const formControl = this.itemTypes().at(index).get('avgCapacity');
formControl.setValue(calculatedResult);
}
Edit:
Since you already have formGroup available in html file, you can simply pass lineItem as 2nd parameter to calculateBCT and access formControl as const formControl = lineItem.get('avgCapacity');
I have a function which should go ahead and update the database on firebase
function editUser() {
var userID = document.getElementById('userID').value;
var editUserField = document.getElementById('editUserField').value;
var newUserValue = document.getElementById('newUserValue').value;
var database = firebase.database().ref().child('users/' + userID);
database.once("value", function(snapshot){
console.log(snapshot.val());
})
database.update({
editUserField: newUserValue
})
}
The above code is sort of working. Its getting the correct user, but whats not happening is the field is not getting updated, but instead, its creating a new field in the database and assigning it the value.
Looks like a key pair value is getting passed in
editUserField: newUserValue
but its actually taking the value editUserField
rather than getting getting it from the input:
var editUserField = document.getElementById('editUserField').value;
The value is actually getting stored correct from:
var newUserValue = document.getElementById('newUserValue').value;
But it doesnot update the value for the correct key, instead creates a new field called editUserField
I need it to get the values from the input and update the fields in firebase.
If I understand your intentions correctly, you want the field that is updated to be the value of editUserField.
As an example, if editUserField is "favorite-food" and newUserValue is "pizza", you want { favorite-food: pizza } to be added to the user's data.
If that's the case, you were very close, you just need to wrap editUserField in square brackets to use it's value:
database.update({
[editUserField]: newUserValue
})
Note: Don't forget to sanitise editUserField! You wouldn't want them setting { isAdmin: true }.
I am using MeteorJS and trying to get the value of a field from MongoDB and assign to a variable. But when want to print to console, it gives all the time 'undefined'. It works fine in HTML template, but i need to store the value in a var in .js file.
var num = ButtonsList.find({_id:'ZcLkjSwNGTpgHkoeq'});
var n = num.button1;
console.log("button number is: "+n);
The code below works fine by the way, if i want them to output in the browser. It outputs the buttons numbers in html using {{}} namespace. But as I said, i need to store the values in variables.
ButtonsList = new Meteor.Collection('list');
Template.theList.helpers({
'buttons': function(){
//return ButtonsList.find().fetch();
return ButtonsList.find('ZcLkjSwNGTpgHkoeq');
}
});
ButtonsList.find() returns a cursor.
ButtonsList.find().fetch() returns an array of buttons.
ButtonsList.findOne() returns will return a single button.
ButtonsList.findOne().fieldName will return the field fieldName of the button that was found.
The reason it works with the {{#each}} template block helper is that each blocks know how to iterate over cursors.
Your using Find , doesnt that mean your getting multiple reccords back? Shouldnt you be using FindOne instead? otherwise youll get an array of objects which means youd have to use num[i].button1 to get to the value.
I am using angular to build a waitinglist-system, where you first join a waitinglist, and then can be moved to the memberlist. I use ng-repeat to fill inn the table with the rows of waiting people, and I assign a button to each row, which can be pressed to move that particular person to the memberlist.
First problem:
I am not sure if i assign the value to the button in the correct way. It is supposed to be the email of the person.
<input type="submit" ng-click="makeMember()" ng-model="member" value="Member" id="{{person.email}}">
Second problem:
I want to use this users email in order to make a sql query to send to the database to move the person to the memberlist (email is primary key).
I am trying to use $scope.member to reference the ng-model, but that only gives me an undefined value.
The makeMember function is just to see if it works (which it doesnt).
$scope.makeMember = function() {
alert("Person email: " + $scope.member);
};
Any help is highly appreciated!
Pass member in like this: ng-click=makeMember(member).
$scope.makeMember = function(member) {
alert("Person email: " + member);
};
Live demo here (click).
The issue you are having is that $scope refers to the controller's scope, not the child scope created by ng-repeat. The only way $scope.member would work is if you had defined it in the controller.
I have an input field like the one below
<input type="hidden" value="" id="inputField">
Now I have list of products and for each product I have a checkbox. When a user clicks on the checkbox, I get the product id and name. Now I want to save it again in the hidden field like below
<input type="hidden"
value="[{"product_id":123,"name":"stack"},{"product_id":456,"name":"overflow"}]"
id="inputField"
>
My first question is how I can do this and how can I create the JSON?
Secondly if the user again unchecks a product checkbox then I need to get the current hidden value and convert it into some data structure, remove the unchecked box id from the data structure and then save it again in the hidden field.
Is there any library which does this job in JavaScript?
Using jQuery:
HTML:
<input type="hidden" value='[{"product_id":123,"name":"stack"},{"product_id":456,"name":"overflow"}]'
id="inputField">
JS:
var data = {}
data.products = jQuery.parseJSON($('#inputField').val())
alert(data.products[0].product_id)
The building block that you look for are JSON.stringify and JSON.parse;
var stringData = '[{"product_id":123,"name":"stack"}, {"product_id":456,"name":"overflow"}]';
// Convert a string to an JavaScript object
var arrayData = JSON.parse(stringData);
// Convert a JavaScript object to a string
stringData = JSON.stringify(arrayData);
Now, whenever one of your checkboxes changes state, you'd get the object from the hidden field and modify it. After the modification of the object, you'd save the string back to the hidden field.
To read and store the value from/to the hidden field:
var field = document.getElementById('inputField');
// Reading the value
stringData = field.getAttribute('value');
// Storing the value
field.setAttribute('value', stringData);
You still lack the modifications of your array which you would do similar to:
// Adding a newly checked product
arrayData.push({
product_id: …,
name: …
});
// Removing a product from the list is more complicated
arrayData = arrayData.filter(function(product){
var productIdToRemove = …;
return product.product_id!==productIdToRemove;
});
Regarding libraries: Probably most do contain code to facilitate array manipulation and setting of form data. See the documentation of jQuery or prototype or the other answers for examples.
Just a thought: Wouldn't it be simpler to discard the whole idea of using the hidden field and transfer the checkboxes to the server instead. If the checkbox was checked, use it, otherwise ignore the correlating product data.
In JavaScript, just assign the value:
var json = JSON.stringify([{"product_id":123,"name":"stack"}]);
document.getElementById('inputField').setAttribute('value', json);
In a server-side language, encode the JSON in HTML, for example with php's htmlspecialchars or python's html.escape. The result will look like this:
<input type="hidden" id="inputField"
value="[{"product_id":123,"name":"stack"}]">
As it is stated in other answers below, to convert JSON to string, use JSON.stringify() function like so:
var json = JSON.stringify([{"product_id":123,"name":"stack"}]);
document.getElementById('inputField').setAttribute('value', json);
And you get string representation of JSON object in var json. To do this other way round so you can update the actual JSON object contained in that string, you can use eval:
var json_object = eval("("+json+")");
Now, original JSON object is recreated, and you can update it, and re-strigify it back to hidden field or some other var...
I am still a bit confused about your question, but if you are simply storing the name and id from the input checkboxes which are checked you can do this quite simply using jQuery.
var jsonArray = [];
$("input:checkbox:checked").each(function(){
var jsonObj = {};
jsonObj.product_id = $(this).attr("id");
jsonObj.name = $(this).attr("name");
jsonArray.push(jsonObj);
});
The variable jsonArray will now hold a json string similar to the example you have posted. You can use JSON.stringify(jsonArray) to see this.
There is no need to create the hidden field, holding this string as the value and trying to add and remove from it as checkbox states change. Simply execute the javascript when the page is ready to change via button click, etc.
Best of luck.
I would suggest to use the encodeURIComponent function. Together with the JSON.stringify we should have something like the following:
var data= "{"name":"John"}";
var encodeddata encodeURIComponent(JSON.stringify(var data= "{"name":"John"}";
))
Now that value can be safely stored in an input hidden type like so:
<input type="hidden" value="'+encodeddata+'">
Now to read the data back we can do something like:
var data = JSON.parse(decodeURIComponent(value))
If you have a JSON object, save it to the hidden field using JSON.stringify:
var myObj = [{"product_id":123,"name":"stack"},{"product_id":456,"name":"overflow"}];
document.getElementById('inputField').value = JSON.stringify(myObj);
Add library
"<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>"
Use: ${fn:escapeXml(string1)}
input type="hidden" value="${fn:escapeXml(string1)}" id="inputField"