Buildling an array of vaules from page elements in JQuery/Javascript - javascript

I have a set of text boxes in which the user inputs an email address into each one. I want to loop around these and build an array of them. How do I do it?
var emailAddresses = new Array();
$(".email_address").each(
function() {
//add this $(this).val() emailAddresses
}
);

var emailsArr = $('.email_address').map(function(i,n) {
return n.value; //or $(n).val() or $(n).attr('value')
}).get();
See $.map for an awesomely concise way to do this sort of thing. get converts the returned collection into an array. Hope that helped.

Related

How to generate one object key with an array of stored values from multiple on click events using localstorage and Jquery

I'm new to coding, and I need to display past search values from an input field using localstorage. The only way I can think of is by using one object key with an array of stored values from an on click event. Problem is, I can only get one position to appear as a value, with each value generated replacing the last. I've tried for loops and can't seem to get it to work. This is the code I have so far:
$('.search-city').on('click', function(e){
e.preventDefault();
var textArr = [];
var text = $(".form-control").val();
textArr.push(text);
localStorage.setItem("value1", textArr);
});
$('.search-city').on('click', function(e){
e.preventDefault();
var search = localStorage.getItem("value1")
This would work:
$('.search-city').on('click', function(e){
e.preventDefault();
// get the value from local storage
var localValue = localStorage.getItem('value1');
// if we had a value, parse it back to an array, if we dont, create an empty array
var textArr = localValue ? JSON.parse(localValue) : [];
// get the text from the search input, dont use "form-control"
// you're likely to have several of those on the page
// give the element a custom class like "search-input" and use that (id would be even better)
var text = $('.search-input').val();
// add the text to the array
text = trim(text);
if (text) {
textArr.push(text);
}
// enforce a size limit here by removing the 0 index item if the count has grown too large
var maxAllowed = 10;
while (textArr.length > maxAllowed) {
textArr.shift();
}
// localstorage can only hold simple strings so we'll JSON stringify our object and store that
localValue = JSON.stringify(textArr);
localStorage.setItem("value1", localValue);
});

How to make jQuery .map only add filled inputs to array?

So here is my jQuery:
var optionsArray = $(".optionInput").map(function() {
return this.value;
}).get();
Currently it gets all of the inputs with the class .optionInput and puts the data into an array, but it also stores blank inputs too. With my site I don't need all the inputs to be filled, but I don't want the function to collect any data from the blank fields. Any help would be much appreciated.
If the function returns null or undefined, no element will be inserted
source: jQuery
var optionsArray = $(".optionInput").map(function() {
return this.value || null;
}).get();
Jsfiddle Demo

Issue with JSON stringify?

/* Helper function to clean up any current data we have stored */
function insertSerializedData(ids, type) {
// Get anything in the current field
current_data = $('#changes').val();
if (!current_data) {
var data = new Array();
data[type] = ids;
$('#changes').val(JSON.stringify(data));
} else {
var data = JSON.parse($('#changes').val());
data[type] = ids;
$('#changes').val(JSON.stringify(data));
}
console.log($('#changes').val());
}
I am using the following function to either add data to a current JSON object or create a new JSON object all together to be used in PHP later. Is the stringify() method only for FF? I am using google chrome and I am being given an empty object when using the conosole.log() function...
Also what happens if you try to store two values with the same key? I assume it will overwrite...so I should add a random math number at the end array in order to keep duplicates from showing up?
Thanks :)
These lines may cause problems:
var data = new Array();
data[type] = ids;
... because arrays in JavaScript are not quite like arrays in PHP. I suppose what you meant is better expressed by...
var data = {};
data[type] = ids;
Besides, current_data seems to be local to this function, therefore it also should be declared as local with var. Don't see any other problems... except that similar functionality is already implemented in jQuery .data() method.
UPDATE: here's jsFiddle to play with. ) From what I've tried looks like the array-object mismatch is what actually caused that Chrome behavior.
I reformatted it a bit, but and this seems to work. It will set the "value" attribute of the #changes element to a JSON string. I assume that the type argument is supposed to be the index of the array which you're trying to assign?
function insertSerializedData(ids, type) {
var changes = jQuery('#changes'), arr, val = changes.val();
if (!val) {
arr = [];
arr[type] = ids;
changes.val(JSON.stringify(arr));
} else {
arr = JSON.parse(val);
arr[type] = ids;
changes.val(JSON.stringify(arr));
}
console.log(changes);
}

Does jQuery have a collect method

I have this code
var selected = new Array();
$(".client_associates_users input:checked").each(function(index) {
selected.push($(this).val());
});
and it works great but i was wondering if jQuery had a collect so i would not have to create an array and push to it.
I basically want all the values of the checked input fields
jQuery offers the .map() method,
var selected = $(".client_associates_users input:checked").map(function(index) {
return this.value;
}).get();
This method will create a new array out of whatever data you return from within the callback. Be aware that you need to call .get() at the end to get a real array.
Ref.: .map()
Yes, $.fn.map http://api.jquery.com/map/ or $.map http://api.jquery.com/jQuery.map/
var $checkboxes = $(".client_associates_users input:checked"),
selected = $checkboxes.map(function(i){
return $checkboxes.eq(i).val();
}).get();
or this for $.map (I prefer this one)
var $checkboxes = $(".client_associates_users input:checked"),
selected = $.map($checkboxes, function(el,i){
return $checkboxes.eq(i).val();
});
Update
No longer recreates a jQuery object on each iteration.
The jQuery object $(".client_associates_users input:checked") is an array so you should just be able to access those values if you append a .val() to the end of that selector.

Object - An Object in the Object - An array of those Objects

I'm new to javascript so let me just say that right up front.
A web site I frequent has 50 or so items, with details about that item, in a table. Each table row contains several td cells. Some rows have types of things that are similar, like USB drives or whatever. I want to capture each row so that I can group and reorder them to suit my tastes.
I have this object:
function vnlItemOnPage(){
this.Category = "unknown";
this.ItemClass = "vnlDefaultClass";
this.ItemBlock = {};
}
This represents one row.
What I've been trying to figure out is how to capture the block of html < tr>stuff< /tr> and save it into this.ItemBlock.
That part is pretty easy:
vnlItemOnPage.ItemBlock = element.getElementByClassName('className')[0]
?
That seems pretty straight forward. Am I missing something?
This part I am stuck:
There'll be 50 of them so I need an array of vnlItemOnPage?
vnlAllItems = ???
var vnlAllItems = [vnlItemOnPage]?
And, how would I add to the array and delete from the array? I probably wont delete from the array if that is complicated don't bother with it.
Once I capture the < tr> html, I can just append it to a table element like so:
myTable.appendChild(vnlAllItems[0].ItemBlock);
Correct?
I'm open to any suggestions if you think I'm approaching this from the wrong direction. Performance is not a big issue - at least right now. Later I may try to conflate several pages for a couple hundred items.
Thanks for your assistance!
[edit]
Perhaps the second part of the question is so basic it's hard to believe I don't know the answer.
The array could be: var vnlAllItems = []
And then it is just:
var row1 = new vnlItemOnPage;
vnlAllItems.push(row1);
var row2 = new vnlItemOnPage;
row2.ItemBlock = element.getElementByClassName('className')[0];
I'd like to close the question but I hate to do that without something about handling the array.
JQuery is your friend here.
This will give you the inner HTML for the first row in the body of your desired table:
var rowHtml = $('table#id-of-desired-table tbody tr:first').html() ;
To get the outer HTML, you need a jQuery extension method:
jQuery.fn.outerHTML = function() {
return $('<div>').append( this.eq(0).clone() ).html();
};
Usage is simple:
var rowHtml = $('table#id-of-desired-table tbody tr:first').outerHtml() ;
Enjoy!
Not sure if it is what you are looking for, but if I wanted to manipulate table rows I would store:
Row's whole html <td>1</td>...<td>n</td> as string so I can quickly reconstruct the row
For each row store actual cell values [1, ..., n], so I can do some manipulations with values (sort)
To get row as html you can use:
var rowHtml = element.getElementByClassName('className')[0].innerHTML;
To get array of cell values you can use:
var cells = [];
var cellElements = element.getElementByClassName('className')[0].cells;
for(var i=0;i<cellElements.length;i++) {
cells.push(cellElements[i].innerText);
}
So the object to store all this would look something like:
function vnlItemOnPage(){
this.Category = "unknown";
this.ItemClass = "vnlDefaultClass";
this.RowHtml = "";
this.RowCells = [];
}

Categories

Resources