filling javascript object "on the fly" - javascript

HI, i have an object: var myobject = new Object;
and i want to dynamically fill it with properties while looping through jquery input collection in that manner:
$('.test').each(function(){
myobject.$(this).attr('name') = $(this).val();
});
what i'm doing wrong here?
thanks in advance

Try this:
$('.test').each(function () {
var e = $(this);
myobject[e.attr('name')] = e.val();
});
Objects in JavaScript can be accessed using object.property or object['property'] (these two are equivalent). The latter allows you to use expressions (like variables): object[propertyName].

With the way you are doing it:
var myObject = {};
$('.test').each(
function(){
var elem = $(this);
myObject[elem.attr('name')] = elem.val();
}
);

Related

Jquery getting nested inputs of Div, placing in Object

I am at my wits end with this nested loop.
I am trying to create an object with nested objects in it grouped by the containing div id.
So far this is what I have:
$('#survey-submit').on('click', function (e) {
var formData = {};
var item = {};
$("div[id^='question-']").each(function () {
var id = '#' + $(this).attr('id');
var $this = $(this);
formData[id] = $this.children('input, select,checkbox').each(function () {
item[this.name] = this.value;
});
//console.debug(formData);
});
console.debug(formData);
return false;
});
The result of the console log is all the input elements of the divs that have the start like question, I get the expected number of new objects all dynamically named, but they all contain the same thing.
The contents of each object are not specific to the this object I am trying to generate it from, any help would be appreciated!
I found a solution to the problem here : jquery how to get form element types, names and values
I wound up doing this:
$("div[id^='question-']").each(function () {
var id = '#' + $(this).attr('id');
var $this = $(this);
var inputs= $(id+' :input').map(function(index, elm) {
return {name: elm.name, value: $(elm).val()};
}).get();
formData[id]=inputs;
});

Changing the selected object in Javascript

What I am trying to do is rewrite content on the page depending on which object I have selected. I have some objects like so:
function floorPlan(name,rev,sqft,bedrm,bthrm) {
this.name = name;
this.rev = rev;
this.sqft = sqft;
this.bedrm = bedrm;
this.bthrm = bthrm;
}
// 1BR Plans
var a1 = new floorPlan('A1',false,557,1,1);
var a2 = new floorPlan('A2',false,652,1,1);
var a3 = new floorPlan('A3',false,654,1,1);
var a4 = new floorPlan('A4',false,705,1,1);
var a5 = new floorPlan('A5',false,788,1,1);
// The Selected plan
var currentPlan = floorPlan.a1;
I am having the user control this via a .click() function in a menu:
$('.sideNav li').click(function() {
// Define the currentPlan
var current = $(this).attr('id');
var currentPlan = floorPlan.current;
});
The problem is that currentPlan keeps coming back as undefined and I have no idea why. Should I be defining currentPlan differently? I can't seem to find any resources to help me find the answer.
UPDATED:
I switched out a few parts per your suggestions:
// The Selected plan
var currentPlan = a1;
and....
// Define the currentPlan
var current = $(this).attr('id');
currentPlan = current;
However, everything is still returning undefined in the click function (not initially though).
First of all $('this') should be $(this)
Secondly you're trying to use a read ID from your LI as a variable name. That doesn't work. If you store your plans in an array you can use the ID to search in that array:
var plans=Array();
plans["a1"]=new floorPlan('A1',false,557,1,1);
plans["a2"]=new floorPlan('A2',false,652,1,1);
Then your jQuery code should be altered to this:
$('.sideNav li').click(function() {
// Define the currentPlan
var current = $(this).attr('id');
var currentPlan = plans[current];
alert(currentPlan);
});
I created a JSFiddle for this. Is this what you were looking for?
Use as floorPlan.currentPlan = a1;
instead of var currentPlan = floorPlan.a1;
Please create a plunker and will correct if any issue.
I spot two errors.
When you write var inside a function, that variable is only accessible with that function. Right now you are creating a new variable in your anonymous function that is "hiding" the global variable with the same name.
So, first remove the var keyword from the assignment in the anonymous function (the one you call on "click").
Secondly I think you mean to assign floorPlan[current].
The final line should read:
currentPlan = floorPlan[current];

How to add a variable to a javascript/jQuery object?

Well, the problem is quite simple. I got an object of parsed table rows. Code for it is this:
var erg = [];
$("tr").each(function (index) {
var row = {};
var test = $(this).children();
row['column1'] = test[0].textContent;
row['column2'] = test[1].textContent;
row['column3'] = test[2].textContent;
row['column4'] = test[3].textContent;
row['column5'] = test[4].textContent;
row['column6'] = test[5].textContent;
row['column7'] = test[6].textContent;
erg.push(row);
});
And I wanna pass a variable var my_variable="blabla" to it without ruining the structure of the object. So how could i bring that object into a structure like this?:
Object{my_variable="my_variable_value"}, Object{my_table=[Object{...}, Object{...}]} //all the objects of the table
$.extend({}, erg, my_variable); only messed my object up.
I want it in that structure so i can pass it as json to my php script and filter my variable easily. Any tips, links, code snippets? :)
I'm not sure at which point you want to add that, but you may simply wrap your array with another object, and add your property to that same object.
This is basically what Florent's answer does, but using an object literal instead of a "class" and prototype:
// (your current code)
var wrapper = {
my_variable: 'something',
my_table: erg
};
You can define a class and add the needed variables to its prototype.
First you need a little utility to do that:
function createSharedStruct() {
// Define a shared structure
var Struct = function() {};
// Define a method to define a shared variable
Struct.share = function(variable, value) {
Struct.prototype[variable] = value;
};
return Struct;
}
And then, update your code:
// Create the shared structure
var rowClass = createSharedStruct();
// Register your shared variables
rowClass.share('my_variable', 'my_variable_value');
var erg = [];
$("tr").each(function (index) {
var test = $(this).children();
// Create a new row
var row = new rowClass();
row['column1'] = test[0].textContent;
row['column2'] = test[1].textContent;
row['column3'] = test[2].textContent;
row['column4'] = test[3].textContent;
row['column5'] = test[4].textContent;
row['column6'] = test[5].textContent;
row['column7'] = test[6].textContent;
erg.push(row);
});
// No matter when you share a variable, it will be defined among
// all instances of the same struct.
rowClass.share('my_other_var', 42);
Now you can access shared variables:
console.log(erg[0].my_other_variable); // 42
console.log(erg[1].my_other_variable); // 42
Demo available on JSFiddle.

Selecting javascript objects via their methods with jquery

How would I select:
object.id2 == "name1";
with jQuery (instead of looping through all of the objects and finding the one who's id2 matches "name1"), so I could write something like:
$("name1");
or maybe:
$(object + " name1");
or possibly:
$(object).attr('id2','name1');
You can use Lodash:
var namedObjects = _.find(allObjects, { id2: 'name1' });
var myObj = $('[id2="name1"]')
//myObj will be an array if there is more than one element that matches
As seen here: jQuery Selector API
This might not be the best way to do it, but if you insist on doing it with jquery, this would be the way to do it:
var theArr = [{id2:"name0"},{id2:"name1"}];
var myObj = $(theArr).filter(function(){
return this.id2 === "name1";
}).get(0);
console.log(myObj); // Object {id2: "name1"}
http://jsfiddle.net/Tentonaxe/kTxkr/
of course, if you don't have to support IE<9, you can cut jquery out without changing much:
var theArr = [{id2:"name0"},{id2:"name1"}];
var myObj = theArr.filter(function(obj){
return obj.id2 === "name1";
})[0];
console.log(myObj); // Object {id2: "name1"}
http://jsfiddle.net/Tentonaxe/kTxkr/1
I'm not sure I completely understand your question, but if you create an object like this:
var foo = {id2 : "name1"};
You can use a jQuery selector like this:
$(foo)

How to convert input name to JavaScript array

I have an issue related to converting html inputs names to a javascript object.
For example I have an input:
<input type="checkbox" name="product[1]">
<input type="checkbox" name="product[2]">
and I have javascript code:
var data = {};
$('input').each(function(){
// need to do something like
data[$(this).attr('name')] = $(this).attr('checked');
})
I expect to get data object like this;
data = {
product: {
1: 'checked',
2: 'checked'
}
}
Is this possible without using regular expressions?
Replacing your variables with literal values, you get this:
data["product[1]"] = true;
The square brackets have no meaning as they are inside a string, so you won't get any result.
There are ways around this. You could use eval: eval("data."+this.name+" = "+(this.checked?"true":"false"));
However since eval is best avoided, try this:
var m = this.name.match(/(.*)\[(\d+)\]/);
data[m[0]][m[1]] = this.checked;
Yes in general it is possible. You can do the following:
var noregexp = $(this).attr('name').split("[");
if (noregexp.length==2) {
//should be
var the_name = noregexp[0];
var the_index = noregexp[1].substr(0,noregexp[1].length-1); //this will get the index with removed ]
}
I made this up from my mind. It's not a beautiful solution but one without regexp as you wished.
You can get a data structure the way you need using:
var data = {product: []};
$('input').each(function(){
data.product[$(this).attr('name').match(/product\[([\d]*)\]/)[1]] = $(this).prop('checked');
})
console.log(data);
Check thid demo

Categories