How best can I querySelectorAll inputs by their name in Javascript - javascript

I'm trying to populate an array with html input field names then further match them to json object names to I can assign values into them at once as below
Kindly assist with a proper querySelectorAll(input) to get input fields by their name instead of their class names as the below is doing
var inputs = Array.prototype.slice.call(document.querySelectorAll('input'));
Then reuse in code below
Object.keys(recipient).map(function (dataItem) {
inputs.map(function (inputItem) {
return (inputItem.name === dataItem) ? (inputItem.value = recipient[dataItem]) : false;
});
});
My data looks like so:
"data": {
"type": "beneficiaries",
"id": "C9QV9ZNZ",
"attributes": {
"bank_name": null,
"last_name": "xcxc",
"beneficiary_type": "MT",
"mobile_money_msisdn": null,
"branch_name": null,
"recipient_type": "P",
"first_name": "dfgdf",
"middle_name": null,
"name": "dfgdf xcxc",
"mobile": null,
"account_number": "111111111"
}

The nested loops is overkill. Just loop over the inputs and see if the key exists in the object.
var data = {
name1: 123,
name2: 345,
name3: 678
}
document.querySelectorAll("input[name]").forEach( function (input) {
var name = input.name;
if (data[name]) input.value = data[name]
})
<form>
<input name="name1" />
<input name="name2" />
<input name="name3" />
</form>

Related

how to replace object values from input values with JavaScript

When I input values in input fields it has to set all values to my object but it doesn't do that.
So how can I set values of an object using input fields like this please make it workable...
Please make it as when I click the pay button it set all values of input to the object.
<input type="text" id="name"></input>
<input type="email" id="email"></input>
<input type="number" id="phone"></input>
<input type="text" id="billing"></input>
<input type="number" id="amount"></input>
<button id="rzp-button1">Pay</button>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
var nameUser = document.getElementById("name").value;
var emailUser = document.getElementById("email").value;
var phoneUser = document.getElementById("phone").value;
var billingAddress = document.getElementById("billing").value;
var amount = document.getElementById("amount").value;
var options = {
"key": "rzp_test_StY5fFXoMJvNaJ", // Enter the Key ID generated from the Dashboard
"amount": amount*100, // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise
"currency": "INR",
"name": "Trendy Cart",
"description": "Test Transaction",
"image": "https://example.com/your_logo",
// "order_id": "order_9A33XWu170gUtm", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1
"handler": function (response){
alert(response.razorpay_payment_id);
alert(response.razorpay_order_id);
alert(response.razorpay_signature)
},
"prefill": {
"name": nameUser,
"email": emailUser,
"contact": phoneUser
},
"notes": {
"address": billingAddress
},
"theme": {
"color": "#F37254"
}
};
var rzp1 = new Razorpay(options);
document.getElementById('rzp-button1').onclick = function(e){
rzp1.open();
e.preventDefault();
}
</script>
Move the definition of options and rzp1 inside the onclick function. This way the values are only read when the button is clicked and the Razorpay constructor can be passed the values when they are filled in rather than as soon as the page loads.

Typescript Filter and return single key

I have a set of checkboxes that allow a user to check which roles to assign to a new user. I am able to filter back and get only the checkboxes that are actually checked, however, I am having trouble finding the best way to just return the "name" key of those checked checkboxes.
userToAdd.roles = this.roles.filter( (role) => role.checked );
Is there a way to use a reduce, or basically just say "role.name" in the filter so I don't return the entire object? I can do this with a for loop, but I'm curious if there is a better way to just return the name key as part of the filter?
This is how the object looks now, which is wrong:
{
"firstName": "sfsdfds",
"username": "fdsfsdf",
"lastName": "sdfsdfsdf",
"email": "dsfsdfdsf",
"roles": [
{
"ID": "ce97fb46-7e04-4a4f-b393-5a5492b558fb",
"name": "admin",
"checked": true
},
{
"ID": "e89bacd2-4140-46a1-9a2b-0f85aa9f9ca0",
"name": "offline_access",
"checked": true
}
],
"password": "pass"
}
This is how the object should look, in the roles array i just include the name, not the ID or checked keys:
{
"firstName": "testing",
"lastName": "testing",
"username": "testing",
"email": "testing",
"roles": [
"uma_authorization",
"offline_access"
],
"password": "pass"
}
you could map after filtering. i.e:
userToAdd.roles = this.roles.filter( (role) => role.checked ).map(role => role.name;
You can achieve this using array map() method and object destructuring like:
userToAdd.roles = this.roles.filter(({checked}) => checked).map(({name}) => name);
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
Yes you can use reduce.
const data = {
"firstName": "sfsdfds",
"username": "fdsfsdf",
"lastName": "sdfsdfsdf",
"email": "dsfsdfdsf",
"roles": [
{
"ID": "ce97fb46-7e04-4a4f-b393-5a5492b558fb",
"name": "admin",
"checked": true
},
{
"ID": "e89bacd2-4140-46a1-9a2b-0f85aa9f9ca0",
"name": "offline_access",
"checked": true
},
{
"ID": "e89bacd2-4140-46a1-9a2b-0f85aa9f9ca0",
"name": "offline_access2",
"checked": false
}
],
"password": "pass"
}
let filtered = data.roles.reduce((acc, curr)=>{
if(curr.checked) {
acc.push({
name: curr.name
})
}
return acc;
}, []);
console.log(filtered);
.filter().map() would also works but with reduce you don't have to iterate over array twice.
If you have linq, this is another option:
userToAdd.roles = from(this.roles).where(role => role.checked ).select(role =>role.name).toArray();
You can also use this:
this.roles.filter( (role) => role.checked )[0].anyPropert;

How to count total and null values in AngularJs object

I'm trying to count total not null fields out of total fields in my angularjs object, then I want to calculate the percentage.
eg:
in my object contain 10 fields.two fields have some values(others null).
Completed = (not null fields/total fields)*100
= (4/11)*100 = 36.36%
my controller
myApp.controller('PController', function ($scope,localStorageService) {
$scope.user = localStorageService.get("user");
console.log(Object.keys($scope.user).length);
});
now i can get total fields.but how can i count not null fields and callculate percentage?
$scope.user object is like below
{
"user_id": "205",
"first_name": null,
"last_name": null,
"email": "at#yuib.com",
"address": null,
"mobile": null,
"phone": null,
"profile_img": null,
"gender": null,
"registered": "1",
"addresses": 0
}
simple filter method with Object.keys on the $scope.user should give the required result
Object.keys($scope.user).filter(x=>$scope.user[x]!==null).length
Try this:
Object.values($scope.user).filter((item) => item != null).length

How to Fill a Form with Data from a JSON

I have two file, a JSON storing some data and a simple html form.
I want to fill the form with random data taken from a JSON. Those data should be relative to the same object.
My form looks like:
<form id="first_form">
Name:<br>
<input id="name" type="text" name="name">
<br>
Phone:<br>
<input id="phone" type="number" name="phone">
<br>
City:<br>
<input id="city" type="text" name="city">
<br>
Pcode:<br>
<input id="pcode" type="number" name="pcode">
Note:<br>
<input id="note" type="text" name="note">
<br>
</form>
My JSON looks like:
users: [
{
"name": "name1",
"phone": "111111111",
"address": "address1",
"city": "city1",
"pcap": 1111,
"note": ""
},
{
"name": "name2",
"phone": "222222222",
"address": "address2",
"city": "city2",
"pcap": 2222,
"note": ""
},
{
"name": "name3",
"phone": "333333333",
"address": "address3",
"city": "city3",
"pcap": 3333,
"note": ""
},
{
"name": "name4",
"phone": "44444444",
"address": "address4",
"city": "city4",
"pcap": 4444,
"note": ""
}
]
Is there a way to do so in a no-jQuery way?
I hope it is users = rather than users :. Also change id 'pcode' to 'pcap'
In that case you can use the following code
var indx = Math.floor(Math.random()*users.length);
var randUser = users[indx];
for(prop in randUser) {
document.getElementById(prop).value = randUser[prop];
}
There are non-jquery (or other framework) ways to do this, but they are quite tedious (thats why these frameworks exists).
In addition: How would your fill a "single" form with an ARRAY of objects? you will either need to repeat the form or have some way of selecting which dataset you want.
One easy way to fill a form from a json is https://github.com/corinis/jsForm
(disclaimer: I am the author of that module)
If you really want to do it the hard way I suggest taking a close look at http://www.w3schools.com/js/js_htmldom.asp
You need to start processing the complete DOM and identify which form-fields match input and have to worry about the cross-browser dom implementation issues.
Basically you start with getting the "root" of where you want to start parsing:
var root = document.getElementById("first_form");
and then have a recursive function that goes through all children and its childrent to identify a form, which you can then check against your object:.
function replace(root, obj) {
var children = root.childNodes;
for(var i = 0; i < children.lenght; i++) {
var child = children[i];
// go deep
if(child.children) {
replace(child, obj);
}
// check if we have a name attribute - then assume its a form and set its value
if(child.getAttribute("name")) {
child.setAttribute("value", obj[child.getAttribute("name")]);
}
}
}
You can extend the code to also allow sub-objects or other peculiarities in your object.
Going the other way round (doing a for-in in your object and searching for fields) also works and is less code, but that only works for very simple objects.

Bind JSON to Angularjs input

I got some JSON like this:
[{
"Id": 0,
"Text": "Item 1",
"Selected": 1
}, {
"Id": 1,
"Text": "Item 2",
"Selected": 1
}]
And an Input like this:
<input type="text"
value="{{question.postObjs}}"
What I want is the only the property "Text" as a list in the input.
Item 1, Item 2, ...
Is this even possible? I trying around like a while, got nothing to work :-(
in your controller :
scope.text = '';
for (var value in scope.question.postObjs){
scope.text = scope.text + value.Text;
}
in your input :
<input type="text" value="{{text}}" />
or
<input type="text" ng-model="text" />
Write a method in AngularController like this
$scope.getText(){
// which will return ["Item1", "Item2"]
}
And in view you can use the method to populate the value.

Categories

Resources