I have the following JavaScript I am using to save selected check boxes:
function SubmitCheckBoxes()
{
alert("test");
var selectedIDs = [];
var x = 0;
a = document.getElementsByTagName("input");
for (i = 0; i < a.length; i++) {
if (a[i].type == "checkbox" ) {
if (a[i].checked) {
alert(a[i].value);
selectedIDs[x] = a[i].value;
x++;
}
}
}
$.post('./Courses/SaveAndRedirect', selectedIDs, function (data) { });
}
However when I look at the form data being submitted all its says is undefined: undefined for each element in the array.
Not sure what the problem is here.
It is the data attribute in the jquery post method that is wrong. It can't take an array as a parameter. Here is the documentation
data map or string that is sent to the server with the request.
Try using a object literal instead:
$.post('./Courses/SaveAndRedirect', {selectedIDs: selectedIDs}, function (data) { });
I would also try writing selectedIDs[x] = a[i].value; differently:
selectedIDs.push(a[i].value);
I think the problem may be that your post variables are associated with just a numeric instance rather than a field name
You can try something like this:
var selectedIDs = [];
$('input[type="checkbox"]:checked').forEach(function(i, e){
selectedIDs.push($(e).val());
});
$.post('./Courses/SaveAndRedirect', selectedIDs, function (data) { });
Related
I'm writing a test in postman where I want to check if a JSON return contains the Label called 'RegressieMapTest'. This is my script:
pm.test("Is the folder created correctly?", function(){
var jsonData = pm.response.json();
var objString = JSON.stringify(jsonData);
var obj = JSON.parse(objString);
for (var i = 0; i < obj.Corsa.Data.length; i++){
if (obj.Corsa.Data[i].Label == "RegressieMapTest"){
console.log(obj.Corsa.Data[i].Label);
pm.expect(obj.Corsa.Data.Label).to.eql("RegressieMapTest");
}
}
pm.expect.fail();
})
But it doesn't quite work, every time I run this script it seems like it automatically jumps to pm.expect.fail() which is weird because 'RegressieMapTest' is inside the JSON return. Postman returns the following message:
Is the folder created correctly? | AssertionError: expect.fail()
pm.respose.json() is equalent to JSON.parse you don't have to do it again
also you can use array.find method instead of looping through it
pm.test("Is the folder created correctly?", function () {
var jsonData = pm.response.json();
pm.expect(obj.Corsa.Data.find(elem => elem.Label === "RegressieMapTest")).to.be.not.undefined
}
if array has any element with label RegressieMapTest then it will return that data elese returns undefined, so we are validating that it will not return undefined. Meaning it has the value
Your pm.expect.fail(); always runs. You want it to run only when you don't find the field. So just add a flag in your check block.
pm.test("Is the folder created correctly?", function(){
var jsonData = pm.response.json();
var objString = JSON.stringify(jsonData);
var obj = JSON.parse(objString);
var isFound = false;
for (var i = 0; i < obj.Corsa.Data.length; i++){
if (obj.Corsa.Data[i].Label == "RegressieMapTest"){
console.log(obj.Corsa.Data[i].Label);
pm.expect(obj.Corsa.Data.Label).to.eql("RegressieMapTest");
isFound = true;
}
}
if (!isFound) {
pm.expect.fail();
}
})
I am new to Angular js,
I have the following code which binds data to the div,
app.filter("myfilter", function () {
return function (data, catName) {
if (angular.isArray(data) && angular.isString(catName)) {
var rs = [];
var key = {};
for (var i = 0; i < data.length; i++) {
var currdata = data[i][catName];
if (angular.isUndefined(key[currdata])) {
key[currdata] = true;
rs.push(currdata);
}
}
return rs;
}
else
return data;
}
})
But when i came across the code above i found a line "key[currdata] = true;"
what's this piece of code does?
when i comment this particular line data binding not happening?
Thanks in advance.
This line is just like a mark in order that in the next iteration the condition "angular.isUndefined..." is false and, in that way, it prevents push duplicated values into rs array.
it is simply checking that no duplicate key is pushed into rs
I am stuck in a concept of html5 data attributes. That attributes allows nesting like:
<div data-user--name="John" data-user--surname="Doe"></div>
I have seen plugins in the past (like select2) and some of them use the following similar syntax to make an AJAX call:
<div data-ajax--url="my/url" data-ajax--method="POST">
This code in background converts to a dataset in javascript and it returns something like this:
data = {
ajax: {
url: "my/url",
method: "POST"
}
}
But in the practice, vanilla javascript's dataset and jQuery data() methods return different object content.
Javascript
var el = document.getElementsByTagName("div")[0];
el.innerHTML = "<pre>"+JSON.stringify(el.dataset)+"</pre>";
<div data-ajax--url="my/url" data-ajax--method="POST"></div>
jQuery 1.x
$('div').html("<pre>"+JSON.stringify($('div').data())+"</pre>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div data-ajax--url="my/url" data-ajax--method="POST"></div>
jQuery 2.x
$('div').html("<pre>"+JSON.stringify($('div').data())+"</pre>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-ajax--url="my/url" data-ajax--method="POST"></div>
The code in error seems to be the jQuery 1.x versions, because in 2.x versions jQuery returns the same as vanilla Javascript. I found a related bug so it's confirmed: https://github.com/select2/select2/issues/2969
But I can't find where to construct a nested javascript object with the nested html syntax, like the following example:
{
ajax: {
url: "my/url"
method: "POST"
}
}
Is there any Javascript method, or a polyfill, that makes this kind of objects reading the data-* HTML attributes? Is it possible to parse the data javascript strings (i.e. ajax-Method) and return a nested object (ajax.method) ?
Ran into exact same need, but #artofcode's answer parses only 2 levels. So I had to figure out how to parse unlimited number of levels. Here's my solution without limiting levels, based on original answer.
function parseNestedDataSet(data_set) {
var keys = Object.keys(data_set);
var data = {};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = data_set[key];
var splat = key.split('-');
data = parseNestedDataSetKey(splat, value, data);
}
return data;
}
function parseNestedDataSetKey(keys, value, data) {
data = data || {};
var key = keys[0].toLowerCase();
// Not tested, but should convert to camel case
// var key = keys[0].replace(/-([a-z])/g, function (g) {
// return g[1].toUpperCase();
// });
if (!data[key]) {
data[key] = {};
}
if (keys.length > 1) {
keys.splice(0, 1);
data[key] = parseNestedDataSetKey(keys, value, data[key]);
} else {
data[key] = value;
}
return data;
}
Didn't test it thoroughly, but it works in my case, like:
data-buttons--btn1--title;
data-buttons--btn1--icon;
data-buttons--btn2--title.
function parseDataset(dataset) {
data = {};
for(var i = 0; i < Object.keys(dataset).length; i++) {
var key = Object.keys(dataset)[i];
var value = dataset[key];
var splat = key.split("-");
console.log(key, data, splat);
if(!data[splat[0]]) {
data[splat[0]] = {};
}
data[splat[0]][splat[1]] = value;
}
return data;
}
Untested, but should work. Pass el.dataset into the method, get a data object out like:
data = {
'ajax': {
'Method': 'POST',
'Url': 'my/url'
}
};
The following code throws error. I try to get (alert) the value and options of an Optionset in MS CRM 2013, It successfully shows all the things but after that it shows error. i attached the screen shot that error
function GetOptionsetLable()
{
var OptionSetControl = Xrm.Page.getAttribute("test_613a");
for(var intCounter=0; OptionSetControl .getOptions().length; intCounter++)
{
var backendvalue=OptionSetControl .getOptions()[intCounter].value;
alert(backendvalue.toString());
}
}
function GetOptionsetLable()
{
var OptionSetControl = Xrm.Page.getAttribute("test_613a");
for(var intCounter=0; OptionSetControl .getOptions().length; intCounter++)
{
var backendvalue=OptionSetControl .getOptions()[intCounter].value;
alert(backendvalue.toString());
}
}
Your for loop will never end because you don't tell it when to stop.
OptionSetControl.getOptions().length
should be:
intCounter < OptionSetControl.getOptions().length
Full code:
function GetOptionsetLable()
{
var OptionSetControl = Xrm.Page.getAttribute("test_613a");
for(var intCounter=0; intCounter < OptionSetControl.getOptions().length; intCounter++)
{
var backendvalue=OptionSetControl.getOptions()[intCounter].value;
alert(backendvalue.toString());
}
}
Remember that the value property contains the optionset numeric value, and the .text property the label.
you can also use a shorter for condition:
var options = Xrm.Page.getAttribute("test_613a").getOptions();
for (var i in options) {
alert(options[i].value);
}
I also created a library, you can find here:
OptionSet JavaScript Helper Library
I am trying to create an array and get all values of a form submission and put them in that array. I need to do this because during the .each function of this code I must do additional encryption to all the values per client. This is a form with hundreds of fields that are changing. So it must be an array to work. I tried to do following and several other types like it in jQuery but no dice. Can anyone help? Thanks.
Edit: Posted my working solution. Thanks for the help.
Edit 2: Accept sabithpocker's answer as it allowed me to keep my key names.
var inputArray = {};
//jQuery(this).serializeArray() = [{name: "field1", value:"val1"}, {name:field2...}...]
jQuery(this).serializeArray().each(function(index, value) {
inputArray[value.name] = encrypt(value.value);
});
//now inputArray = [{name: "field1", value:"ENCRYPTED_val1"}, {name:field2...}...]
//now to form the POST message
postMessages = [];
$(inputArray).each(function(i,v){
postMessages.push(v.name + "=" + v.value);
});
postMessage = postMessages.join('&');
Chack serializeArray() to see the JSON array format.
http://jsfiddle.net/kv9U3/
So clearly the issue is that this in your case is not the array as you suppose. Please clarify what this pointer refers to, or just verify yourselves by doing a console.log(this)
As you updated your answer, in your case this pointer refers to the form you submitted, how do you want to iterate over the form? what are you trying to achieve with the each?
UPDATE
working fiddle with capitalizing instead of encrypting
http://jsfiddle.net/kv9U3/6/
$('#x').submit(function (e) {
e.preventDefault();
var inputArray = [];
console.log(jQuery(this).serializeArray());
jQuery(jQuery(this).serializeArray()).each(function (index, value) {
item = {};
item[value.name] = value.value.toUpperCase();
inputArray[index] = item;
});
console.log(inputArray);
postMessages = [];
$(inputArray).each(function (i, v) {
for(var k in v)
postMessages[i] = k + "=" + v[k];
console.log(i, v);
});
postMessage = postMessages.join('&');
console.log(postMessage);
return false;
});
The problem is that #cja_form won't list its fields using each. You can use serialize() instead:
inputArray = jQuery(this).serialize();
Further edition, if you need to edit each element, you can use this:
var input = {};
$(this).find('input, select, textarea').each(function(){
var element = $(this);
input[element.attr('name')] = element.val();
});
Full code
jQuery(document).ready(function($){
$("#cja_form").submit(function(event){
$("#submitapp").attr("disabled","disabled");
$("#cja_status").html('<div class="cja_pending">Please wait while we process your application.</div>');
var input = {};
$(this).find('input, select, textarea').each(function(){
var element = $(this);
input[element.attr('name')] = element.val();
});
$.post('../wp-content/plugins/coffey-jobapp/processes/public-form.php', input)
.success(function(result){
if (result.indexOf("success") === -1) {
$("#submitapp").removeAttr('disabled');
$("#cja_status").html('<div class="cja_fail">'+result+'</div>');
}
else {
page = document.URL;
if (page.indexOf('?') === -1) {
window.location = page + '?action=success';
}
else {
window.location = page + '&action=success';
}
}
})
.error(function(){
$("#submitapp").removeAttr('disabled');
$("#cja_status").html('<div class="cja_fail"><strong>Failed to submit article! Check your internet connection.</strong></div>');
});
event.preventDefault();
event.returnValue = false;
return false;
});
});
Original answer:
There are no associative arrays in javascript, you need a hash/object:
var input = {};
jQuery(this).each(function(k, v){
input[k] = v;
});
Here is my working solution. In this example it adds cat to all the entries and then sends it to the PHP page as an array. From there I access my array via $_POST['data']. I found this solution on http://blog.johnryding.com/post/1548511993/how-to-submit-javascript-arrays-through-jquery-ajax-call
jQuery(document).ready(function () {
jQuery("#cja_form").submit(function(event){
jQuery("#submitapp").attr("disabled","disabled");
jQuery("#cja_status").html('<div class="cja_pending">Please wait while we process your application.</div>');
var data = [];
jQuery.each(jQuery(this).serializeArray(), function(index, value) {
data[index] = value.value + "cat";
});
jQuery.post('../wp-content/plugins/coffey-jobapp/processes/public-form.php', {'data[]': data})
.success(function(result){
if (result.indexOf("success") === -1) {
jQuery("#submitapp").removeAttr('disabled');
jQuery("#cja_status").html('<div class="cja_fail">'+result+'</div>');
} else {
page = document.URL;
if(page.indexOf('?') === -1) {
window.location = page+'?action=success';
} else {
window.location = page+'&action=success';
}
}
})
.error(function(){
jQuery("#submitapp").removeAttr('disabled');
jQuery("#cja_status").html('<div class="cja_fail"><strong>Failed to submit article! Check your internet connection.</strong></div>');
});
event.preventDefault();
event.returnValue = false;
});
});