Variable for each element in array - javascript

Being a rookie at JavaScript, I stumbled upon this simple issue where I need to create an object for each item in an array.
More specifically, I want to create a WYSIWYG text editor for some textareas and then listen to these editor objects for input.
The code for one element would be:
// Make an element a text editor area.
var editorArea = new Edicy.TextEditorView({el: $('.foo')});
// Save on input
editorArea.editor.on('aftercommand:composer', function() {
pageData.set('key', 'value');
});
As I have many of these areas, I would like to use jQuery.each() to initiate these text editors and according unique listeners, using the data-id attribute of the elements:
$('#c-success-tabs-content .tab-pane').each(function(){
var successID = $(this).attr('data-id');
successesList.push(successID);
var editorArea[successID] = new Edicy.TextEditorView({el: $('.foo')});
editorArea[successID].editor.on('aftercommand:composer', function() {
pageData.set('key', 'value');
});
});
As the naming scheme "var editorArea[successID]" and from that the listener "editorArea[successID]" are not possible in JavaScript, what would be the optimum solution?

Use an object:
var editorAreas = {}
$('#c-success-tabs-content .tab-pane').each(function(){
var successID = $(this).attr('data-id');
successesList.push(successID);
editorAreas[successID] = new Edicy.TextEditorView({el: $('.foo')});
editorAreas[successID].editor.on('aftercommand:composer', function() {
pageData.set('key', 'value');
});
});
for(var id in editorAreas){
console.log(id, editorAreas[id])
}

Its just your syntax that is wrong; you can have an array of editors
var editorArea = []; // declare globally
and then
editorArea[successID] = new Edicy.TextEditorView({el: $('.foo')});

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);
});

Iterate through Id's, store values, put into an array

I want to be able to iterate through a number of ids called "#option1", "#option2" etc. The problem is its for an interactive form and I don't know how many options there will be. So I need a way to iterate through the amount in the DOM when the user clicks ("#dothis").
Then I need to get the values of the those options, put into an array called arraylist.
$("#doThis").on("click", function() {
var optionone = $("#option1").val();
var optiontwo = $("#option2").val();
var optionthree = $("#option3").val();
var optionfour = $("#option4").val();
var optionfive = $("#option5").val();
var arrayList = [optionone, optiontwo, optionthree,
optionfour, optionfive];
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
}); // end of dothis click event
As Andy said, give every option the same class. In my example it's "option-item".
$("#doThis").on("click", function() {
var arrayList = [];
$('.option-item').each(function(i) {
arrayList[i] = $(this).val();
});
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
});
Every value is now stored in the array.
see fiddle.
greetings timmi
With your code as is, you can use a selector that selects everything with an ID that starts with 'option', like so [id^="option"], here's how to use it:
$("#doThis").on("click", function () {
var arrayList = [];
$('[id^="option"]').each(function (index, element) {
arrayList.push($(element).val() );
});
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
}); // end of dothis click event

JavaScript Asp.net repeating controls

I am trying to do the folowing with Asp.net 3.5/IIS
A web form with a top level repeatable form. So basically a Order->Products->ProductsParts kinda of scenerio. Order is only one. Product is repeatable. Each product has repeatable products parts. The product and product part have a whole bunch of fields so I cannot use a grid.
So, I have add/remove buttons for Product and within each product add/remove buttons for each product part.
That is my requirement. I have been able to achieve add/remove after some research using jquery/js. How, do i capture this data on the server? Since javascript is adding and removing these controls they are not server side and I don't know how to assign name attributes correctly. I am trying following javascript but it ain't working:
function onAddProperty(btnObject){
var previous = btnObject.prev('div');
var propertyCount = jquery.data(document.body, 'propertyCount');
var newDiv = previous.clone(true).find("*[name]").andSelf().each(function () { $(this).attr("name").replace(($(this).attr("name").match(/\[[0-9]+\]/), cntr)); }); ;
propertyCount++;
jquery.data(document.body, 'propertyCount', propertyCount);
//keep only one unit and remove rest
var children = newDiv.find('#pnlUnits > #pnlUnitRepeater');
var unitCount = children.length;
var first = children.first();
for (i = 1; i < unitCount; i++) {
children[i].remove();
}
newDiv.id = "pnlPropertySlider_" + propertyCount;
newDiv.insertBefore(btnObject);
}
I need to assign name property as array so that I can read it in Request.Form
Fix for not updating ids not working:
var newDiv = previous.clone(true).find("input,select").each(function () {
$(this).attr({
'name': function () {
var name = $(this).attr('name');
if (!name) return '';
return name.replace(/property\[[0-9]+\]/, 'property' + propertyCount);
}
});
}).end().insertBefore(btnObject);
The issue looks like the following line:
$(this).attr("name").replace(($(this).attr("name").match(/\[[0-9]+\]/), cntr));
This statement doesn't do anything. Strings in JavaScript an immutable, and .replace only returns the string with something replaced.
You would then have to actually set the attr("name") to the new string that has the replaced value:
http://api.jquery.com/attr/
I can't help much more without seeing your HTML.

Dynamically create key in JavaScript object

I am trying to dynamically create a key in a JavaScript object with a jQuery selector:
{
$("form").children("input[type=hidden]").attr("name"): $("form").children("input[type=hidden]").val()
}
This is breaking though. Is it possible to dynamically create a key this way?
You can do it in two statements :
var obj = {};
obj[$("form").children("input[type=hidden]").attr("name")]
= $("form").children("input[type=hidden]").val();
I'd personally write it like this to avoid recreating the jQuery set:
var obj = {}, $obj = $("form").children("input[type=hidden]");
obj[$obj.attr("name")] = $obj.val();
Note also that this only makes sense if the jQuery set contains exactly one element.
You can also make it work with multiple fields at once:
var obj = {};
$('form > input[type="hidden"]').each(function (i, el) {
obj[el.name] = el.value;
});
Another more fancy version in case if you have only one hidden field:
var obj = $('form > input[type="hidden"]').serializeArray()[0];

Populate a javascript array with links of a specific class

I'm looking to take a website source and populate an array with a collection of links, filtered by their a class.
Say, for instance, the links were <a class="title">, how could I target each class and add the URL to an array?
Would Javascript or jQuery work better?
var arr = new Array();
$("a.title").each(function()
{
arr.push($(this).attr("href"));
});
So, basically you create an array by using the Array constructor. Then you use JQuery's each method to iterate over the links with class title, getting their urls using the attr method and pushing them in the array along the way.
It's pretty easy with jQuery:
var arr = [];
var ptr = 0;
$('.title').each(function() {
arr[ptr] = $(this).attr('href');
ptr++;
})
Something like
var collectionOfLinks = {};
$('a').each(function() {
var cl = $(this).attr('class');
if (collectionOfLinks[cl] === undefined) {
collectionOfLinks[cl] = [];
collectionOfLinks[cl].push($(this).attr('href'));
}else{
collectionOfLinks[cl].push($(this).attr('href'));
}
});
With this you end up with an object whose properties names are the classes of the <a> elements and whose values are arrays of href
With jQuery, you can do var urls = $("a.title").attr("href")to get what you want.
You can do something like below,
var linkURL = [];
$('a.title').each (function () {
linkURL.push(this.href);
});

Categories

Resources