Returning result from jQuery's .each() - javascript

My "stack" is totally overflow, so I need a help :)
I trying to get all values from FORM and save them to associative array. Here is a code:
var dat = [];
$('form[name=' + form.name + '] input[name], form[name=' + form.name + '] select[name], form[name=' + form.name + '] textarea[name]').each(function(i,el) {
dat[$(this).attr('name')] = $(this).val();
});
I am waiting for all values become in dat after this piece of code, but it looks like dat is internal variable of .each() lambda function, so it is unavailable after .each() is completed.
How to return resulting dat[] from the cycle ?

Try this
function() getFormData(){
var dat = {};
$('form[name=' + form.name + ']').find('input[name], select[name], textarea[name]').each(function(i,el) {
dat[$(this).attr('name')] = $(this).val();
});
return dat;
}
This function will return a json object containing all the form elements name/value pair specified in the selector.

Related

JavaScript get Objects property

Hello guys I've web page which have a lot of scripts, I need to get one by it's name. for e.g 'data'. I need to convert data from this script to one string.
Script is the following:
<script>data = [{'Id': '12344567', 'name': 'TestName','Amount': '1066.00', 'NumberTax': '34.00','tranasactionNumber':'139', 'otherInfo': [{'sku': 'ET|Adult','name': 'Test','category': 'Normal','price': '1032.0', 'quantity':'3'}]}];</script>
This data has array with some elements and another array inside.
Using my script I can only get info and create string with String elements from my data, but how can I get elements from inner array?
var json = '[{';
for (var i in data[0]) {
console.log('type of data[0][i] = ' + typeof data[0][i]);
if (typeof data[0][i] === 'string') {
json = json + '\'' + i + '\'' + ': ' + '\'' + data[0][i] + '\', ';
console.log(i);
console.log(data[0][i])
} else {
//Get infro from inner array
}
}
json = json + '}]';
console.log(json);
Try JSON.stringify(data) to convert object to string instead of your function.
To access the object inside the array you can use the following code:
var obj = data[0]['otherInfo'][0];
You can then use the same code you have above to loop over it and append its elements. If I understand correctly that if what you wish to do.

Pass dynamic json object value from dropdown

I am storing field value (Sales, ProductName) from json in an array named 'data[]' and 'name[]'.
Below is the code which works fine.
function onCompletedCallback(response, eventArgs) {
var chartlist = eval("(" + response.get_responseData() + ")");
var markup = " ";
//Display the raw JSON response
markup += response.get_responseData();
// alert(markup);
var jsonData=jQuery.parseJSON(markup);
// alert(jsonData);
//declaring arrays
var name = [];
var data = [];
$.each(jsonData.d.results, function (index, value) {
data.push(value.Sales);
name.push(value.ProductName);
});
}
Now what I want to pass field values from dropdown(ddlxField) in my UI, which holds all the fieldname of the list and pass it to json object while pushing data in 'name' array.
For now am choosing 'ProductName' form dropdown, i.e, xName=ProductName
var xName = document.getElementById("ddlxField").value;
$.each(jsonData.d.results, function (index, value) {
data.push(value.Sales);
name.push(value.xName); // xname value= ProductName
});
But after execution, xName is coming out to be undefined.
can anyone suggest what else can be done or where am going wrong?
Use value[xName] instead of value.xName.
The [] syntax need a string for key, just like xName.

Passing multiple checkbox values in AJAX call

I use a ternary operator to check which checkboxes in a form have been selected. If a value has been selected, I affix the name-value pair to a query string which is then passed in an AJAX call. If not, I attach a name with an empty string value.
It works fine, I'm just wondering if there's a more compact/elegant way to do this as it seems somewhat verbose. I'm wondering if it's possible to use a for loop. The reason I'm not sure if this would work is it would involve dynamically assigning variable names within the loop based on the index.
var fields = $('input[name="apn"]').serializeArray();
var apn1 = fields[0] ? fields[0]["value"] : ''
query += '&apn1=' + apn1;
var apn2 = fields[1] ? fields[1]["value"] : ''
query += '&apn2=' + apn2;
var apn3 = fields[2] ? fields[2]["value"] : ''
query += '&apn3=' + apn3;
var apn4 = fields[3] ? fields[3]["value"] : ''
query += '&apn4=' + apn4;
var apn5 = fields[4] ? fields[4]["value"] : ''
query += '&apn5=' + apn5;
...
Map the values and indices to an array of objects, and just pass that directly to $.ajax, jQuery will use $.param on it for you :
var fields = $.map($('input[name="apn"]'), function(el, i) {
var o = {};
o['apn' + i] = el.value;
return o;
});
If its just checkboxes:
$('input[name="apn"]').each(function (i, el) {
if($(el).is(':checked')) {
query += '&apn'+i+'=' + el.value;
}
});
You can simply serialize the form:
var query = $("#FormId").serialize();

Use "event's" output as a variable

I have a problem to manipulate checkbox values. The ‘change’ event on checkboxes returns an object, in my case:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
The above object needed to be transformed in order the search engine to consume it like:
{ member,book,journal,new_member,cds}
I have done that with the below code block:
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr=[];
for (var i in value) {
arr.push(value[i])
};
var wrd = new Array(arr);
var joinwrd = wrd.join(",");
var filter = '{' + joinwrd + '}';
//console.log(filter);
//Ext.Msg.alert('Output', '{' + joinwrd + '}');
});
The problem is that I want to the “change” event’s output (“var filter” that is producing the: { member,book,journal,new_member,cds}) to use it elsewhere. I tried to make the whole event a variable (var output = “the change event”) but it doesn’t work.
Maybe it is a silly question but I am a newbie and I need a little help.
Thank you in advance,
Tom
Just pass filter to the function that will use it. You'd have to call it from inside the change handler anyway if you wanted something to happen:
formcheckbox.on('change', function(cb, value){
//...
var filter = "{" + arr.join(",") + "}";
useFilter(filter);
});
function useFilter(filter){
// use the `filter` var here
}
You could make filter a global variable and use it where ever you need it.
// global variable for the search filter
var filter = null;
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr = [],
i,
max;
// the order of the keys isn't guaranteed to be the same in a for(... in ...) loop
// if the order matters (as it looks like) better get them one by one by there names
for (i = 0, max = 5; i <= max; i++) {
arr.push(value["val" + i]);
}
// save the value in a global variable
filter = "{" + arr.join(",") + "}";
console.log(filter);
});

Read from serialize to populate form

I did serialize() on my form and saved the string, is there any function which can populate values back to the form from serialized string?
Here is the updated version of Explosion Pills' answer with the additional suggestions in the comments applied:
$.each(serialized.split('&'), function (index, elem) {
var vals = elem.split('=');
$("[name='" + vals[0] + "']").val(decodeURIComponent(vals[1].replace(/\+/g, ' ')));
});
Check out http://phpjs.org/functions/unserialize:571
I recommend instead of serializing data for communication with javascript, you use JSON. PHP should have json_encode() and json_decode() to help with this, and javascript also has built in JSON handling functions, which you may not even need. For example, if $.getJSON gets a valid JSON string from the server, it will be transformed into a javascript object automatically.
EDIT: assuming you are talking about jQuery's $.serialize(), that I know of there's no function to undo this (I'm not even sure why that would ever be necessary..) but this should work:
$.each(serialized.split('&'), function (index, elem) {
var vals = elem.split('=');
$("[name='" + vals[0] + "']").val(vals[1]);
});
Based on previous answers, if you have checkbox or radio buttons:
$.each(serialized.split('&'), function (index, elem) {
var vals = elem.split('=');
var $elem = $formularioEquipo.find("[name='" + vals[0] + "']");
var value = decodeURIComponent(vals[1].replace(/\+/g, ' '));
if ($elem.is(':radio,:checkbox')) {
$elem.prop('checked', ($elem.val() === value));
} else {
$elem.val(value);
}
});

Categories