Using jQuery to gather data from HTML attributes - javascript

I'm trying to put together a web form to mark an indeterminate number of employees as either present or absent. The page itself contains an arbitrary number of divs of the form:
<div class="employee" empID="9" presence="0">
The divs themselves contain the options, with 'presence' being changed to 1 or 2 using jQuery depending on the option selected.
When the 'submit' button is pressed, I'd like to convert this data into a parsable array of pairs of 'empID' and 'presence'. I've tried doing this with jQuery as follows:
$('.cic-button').click(function(){
var submitData = {employees:[]};
$('firedrill-employee').each(function(){
submitData.push({
employeeID: $(this).attr('empID'),
presence: $(this).attr('presence')
});
});
});
However, when this is done, the submitData variable is failing to populate. Any idea why? Am I going about this in the correct manner? Is what I'm trying to do even possible?
Many thanks.

You have a few errors. Make the class that you iterate over the collection of "employee" not "firedrill-employee" and don't forget the dot to indicate it's a class. Reference the employees array withing the submitData object. You can't just push an element into an object.
$('.cic-button').click(function () {
var submitData = {
employees: []
};
$('.employee').each(function () {
submitData.employees.push({
employeeID: $(this).data('empID'),
presence: $(this).data('presence')
});
});
console.log(submitData);
});
Fiddle

Js fiddle
$('.cic-button').click(function () {
var submitData = [];
$('.employee').each(function () {
var self = $(this);
// Create and obj
var obj = new Object(); // {};
obj["employeeID"] = self.attr("empID");
obj["presence"] = self.attr("presence");
//push that object into an array
submitData.push(obj);
console.log(obj);
console.log(submitData);
});
});

You need to specify the employee array as such:
$('.cic-button').click(function(){
var submitData = {employees:[]}; // employees is an array within submitData...
$('.firedrill-employee').each(function(){
submitData.employees.push({ // ...so amend code here to push to the array, not submitData
employeeID: $(this).attr('empID'),
presence: $(this).attr('presence')
});
});
console.log(submitData);
});
See example JSFiddle - http://jsfiddle.net/yng1qb6o/

Related

How to push value in array to store in chrome storage?

Array push function is creating nested arrays instead of putting values on indexes. its creating nested item in item instead of adding it in the index of array. I tried many ways but did not find the problem.
i want to add array in each index so that i can retrieve it and create its csv.
I want output like this: item[0]=[title,description,price,image]
item1=[title,description,price,image] and so on as per values entered
here is my js:
$(function(){
var title='';
var price='';
var description='';
var image='';
var i=0;
var product =[];
var products=[];
$("#scrape").click(function(){
chrome.storage.sync.get(["key"],function(result){
if(result.key!=undefined){
i=result.key;
}
});
chrome.tabs.query({active:true,currentWindow:true},function(tabs){
chrome.tabs.sendMessage(tabs[0].id,{todo:"fetch"},function(response){
description =response.description;
title=response.title;
image=response.image;
price=response.price;
product=[title,price,image,description];
chrome.storage.sync.get(function(item){
if(item["products"] != undefined){
item["products"].push(product);
}
else{
item["products"]=product;
}
//console.log(item);
chrome.storage.sync.set({item});
i=i+1;
});
});
});
});
});
enter image description here
Think of storage as of a standard JS object that has keys and values. In your case it would make sense to use a key like products which would be a standard JS array. The only conceptual difference with using chrome.storage is that you need to read and write the value separately.
$('#scrape').click(function () {
chrome.tabs.query({active: true, currentWindow: true}, tabs => {
chrome.tabs.sendMessage(tabs[0].id, {todo: 'fetch'}, response => {
chrome.storage.sync.get('products', ({products = []}) => {
products.push([
response.title,
response.price,
response.image,
response.description,
]);
chrome.storage.sync.set({products});
});
});
});
});

Webdriver JS - Store sendKeys to variable and reuse

Currently I have a form with 10 fields that I need to do sendkeys > store the value and after assert this value when save the form. For each of these fields I need to create a function and store the value in a variable or is there a better way?
My actual code:
var email = driver.findElement(By.name('email'));
email.sendKeys('info#domain.com');
email.getAttribute("value").then(function(email_text) {
var email = email_text;
});
Cheers,
Rafael
If I understand correct, the process looks like you should fill some fields, remember their values and check values after the form has been submitted.
There is no one standard decision for tasks like this, it depends on developer.
So, we know which values we need and can store it for example in map
{
'email':'example#email.com',
'telephone':111222333
}
Key is name for finding element, value - for sendKey and checkValue methods.
You should write two methods, which will work with test data map and will fill inputs and check values in cycle by map keys.
Do you mean you want to do this as an array?
// you can represent each field as an object
var fields = [
{ elementName: 'email', expectedText: 'info#domain.com' },
{ elementName: 'password', expectedText: 'bla bla bla' }
];
// sendKeys to each field with the specified text
fields.forEach(function(field) {
browser.driver.findElement(by.name(field.elementName)).sendKeys(field.expectedText);
});
// to get all the field text (from promises) and store it as an array
browser.controlFlow().execute(function() {
var textArray = [];
fields.forEach(function(field) {
browser.driver.findElement(by.name(field.elementName)).getAttribute('value').then(function(actualText) {
textArray.push({elementName: field.elementName, actualText: actualText});
});
});
return textArray;
}).then(function(storedTextArray) {
// do something with the stored text array here
});

store array into localstorage instead of replace

I'm using local storage as below like
var post = {
title: 'abc',
price: 'USD5'
};
window.localStorage['book'] = JSON.stringify(post);
I want to create nested json in my localstorage, if above code is within a click event for the user to click save, it will delete the old data and replace it. How to push new value as an array object?
Use an actual array, e.g. on page load:
var posts = JSON.parse(localStorage['book'] || "[]");
Then as you're working with it, add to the array in memory:
posts.push({
title: 'abc',
price: 'USD5'
});
Any time you want to save the value back to local storage:
localStorage['book'] = JSON.stringify(posts);
Here's a complete functional example (live copy; sadly, Stack Snippets disallow local storage):
HTML:
<div>
<label>
Name:
<input type="text" id="txt-name">
</label>
</div>
<div>
<label>
Price:
<input type="text" id="txt-price">
</label>
</div>
<div>
<input type="button" value="Add" id="btn-add">
</div>
<div id="list"></div>
JavaScript (must be after the HTML in the document):
(function() {
var nameField = document.getElementById("txt-name"),
priceField = document.getElementById("txt-price");
// On page load, get the current set or a blank array
var list = JSON.parse(localStorage.getItem("list") || "[]");
// Show the entries
list.forEach(showItem);
// "Add" button handler
document.getElementById("btn-add").addEventListener(
"click",
function() {
// Get the name and price
var item = {
name: nameField.value,
price: priceField.value
};
// Add to the list
list.push(item);
// Display it
showItem(item);
// Update local storage
localStorage.setItem("list", JSON.stringify(list));
},
false
);
// Function for showing an item
function showItem(item) {
var div = document.createElement('div');
div.innerHTML =
"Name: " + escapeHTML(item.name) +
", price: " + escapeHTML(item.price);
document.getElementById("list").appendChild(div);
}
// Function for escaping HTML in the string
function escapeHTML(str) {
return str.replace(/&/g, "&").replace(/</g, "<");
}
})();
Side note: If there's any chance at all you might have to support your code on older browsers that don't have local storage at some point, you can give yourself the option of using a polyfill that writes to cookies if you use the more verbose .getItem(...)/.setItem(..., ...) API, as they can be polyfilled whereas accessing via [] as in the above can't be.
localStorage supports strings. You should use JSONs stringify() and parse() methods.
If I understood the question and what you are looking for is storing an array and not just an object with properties.
As scunliffe commented, What you can do in order to add items to an array which is stored in the local storage is:
Generating the array with first object:
var array = [];
array[0] = //Whatever;
localStorage["array"] = JSON.stringify(array);
Adding items to the array:
//Adding new object
var storedArray = JSON.parse(localStorage["array"]);
sotreadArray.push(//Whatever);
localStorage["array"] = JSON.stringify(array);
This way you store an JSON object representing an array.
As mentioned in this post
You can also extend the default storage-objects to handle arrays and objects by:
Storage.prototype.setObj = function(key, obj) {
return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
return JSON.parse(this.getItem(key))
}

How to access a predefined array in AngularJS

I'm facing an issue with accessing the array element in AngularJS. I have an array:
$scope.salesentry = [
{
sales_id:'',
product_id: '',
product_category_id:'',
sale_qty:null,
sale_amount:null
}
];
I want to update the sales_id field value on some button click like:
$scope.saveData = function() {
$scope.salesentry.sales_id='10';
});
I'm not able to access it in the above way. How can I do so?
salesentry is an array, so you need to access a specific element on it first using [0].
So your code becomes:
$scope.saveData = function() {
$scope.salesentry[0].sales_id='10';
});
Do you want to update each salesentry's sales_id ?
If yes you may use
angular.foreach($scope.salesentry, function(value, key){
value.sales_id = 10;
});
You need to index the array
$scope.salesentry[0].sales_id = '10'
Also, no need for the comma at the end.

Creating a key/pair object using jQuery and some inputs

I have a cart on my website and I need to let users easily change the quantity of items they have in their cart at a moment.
Here is the javascript code I have so far:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var items = [];
$(".item").each(function () {
var productKey = $(this).find("input[type='hidden']").val();
var productQuantity = $(this).find("input[type='text']").val();
items.addKey(productKey, productQuantity); ?
});
// 1. Grab the values of each ammount input and it's productId.
// 2. Send this dictionary of key pairs to a JSON action method.
// 3. If results are OK, reload this page.
});
</script>
The comments I wrote are just guidelines for me on how to proceed.
Is there a way to add a key/pair element to an array of sorts? I just need it to have a key and value. Nothing fancy.
I wrote in an addKey() method just for illustrative purposes to show what I want to accomplish.
items[productKey] = productQuantity;
In JavaScript, Arrays are Objects (typeof(new Array)==='object'), and Objects can have properties which can be get/set using dot- or bracket- syntax:
var a = [1,2,3];
JSON.stringify(a); // => "[1,2,3]"
a.foo = 'Foo';
a.foo; // => 'Foo'
a['foo']; // => 'Foo'
JSON.stringify(a); // => "[1,2,3]"
So in your case, you can simply the productQuantity value to the productKey attribute of the item array as such:
items[productKey] = productQuantity;
items[productKey]; // => productQuantity
You can add anonymous objects to the items array like:
items.push({
key: productKey,
quantity: productQuantity
});
Then access them later as items[0].key or items[0].quantity.
Also you can use JQuery.data method and like that you can also get rid of those hidden.

Categories