Assigning attributes from an array - javascript

I am trying to build a form based off of column names I get from a PHP script, through AJAX, and a pre-defined array of column details. I am hoping to assign these pre-defined attributes to the incoming columns and build a form. For example, if I ever get the column "UserName" I want to to always be an < input >
The template
var template = {
UserName : {
label: "User Name:",
type: "input"
}
UserId : {
label: "User Id:",
type: "text"
}
}
Incoming JSON array from AJAX request
{"UserName":"bob", "UserId":"1"}
Now I need to somehow 'match' these. I myself am not sure exactly what to do here.
$.each(data, function(i,e){
// if index (such as UserName) is found in template array, maybe add the attributes to it?
});

For your case, use obj.hasOwnProperty(key) to test if it exists, concatenate a string and use a ternary assignment to build a input element. You could also use an if statement if you wished.
var $html = '';
$.each(data, function(idx,v){
$html += template.hasOwnProperty(idx)? '<input type="'+template[idx]['type']+'" name="'+idx+'"/>': '';
});
console.log($html);
Here's your jsFiddle

An alternative (and perhaps wordier) solution including label processing might be shown in this jsFiddle. The high level is based on the following code:
$(function () {
var template = {
UserName: {
label: "User Name:",
type: "input"
},
UserId: {
label: "User Id:",
type: "text"
}
};
var data = {
"UserName": "bob",
"UserId": "1"
};
$.each(data, function (key, value) {
if (template[key] != undefined) {
$("#here").append($("<span>" + template[key].label + "</span>"));
$("#here").append($("<input type=\"" + template[key].type + "\">"));
$("#here").append($("<br>"));
}
});
});

Related

How to separate a JSON.stringify result

Related Retrieve two lists, sort and compare values, then display all the results
The question in the related post was how to combine two lists and sort them. The code referenced each item on each list. So, when I got the result, I could manipulate it.
The best solution used console.log(JSON.stringify(result,null,2)); to return the result, nicely combined and sorted.
Trouble for me is being able to translate that back into something I can work with. I can get the result into a variable and display it on the page, but it's the raw output : [ { "Title": "apple", "Type": "rome", "State": null }, ...
Have tried 'JSON.parse(result);' where result is the variable that is used to handle the combination and sorting of the two lists. All that gives is an invalid character error on the line. Also looked at the 'replace' option. That just confused me, tmi. Tried setting a variable directly on the result (so those who know are laughing) 'var foo = result;' That returns object, object.
The desired end result would be to end up with each item separate so I can put them in a table (or a list) on my html page with blanks in any column where there is no data.
I know there has to be a simple, easy way to do this without 200 lines of transformation code. But I can't find a clear example. Everything I'm seeing is for +experts or uses a super simple array that's typed into the code.
Is there a way to attach something like this (from my original) to the result instead of using JSON.stringify? What other step(s) am I missing in being able to extract the fields from JSON.stringify using JSON.parse?
}).success(function (data) {
var title = '';
var type = '';
$.each(data.d.results,
function (key, value) {
title += "Title: " + value.Title + "<br/>";
type += "Type: " + value.Type + "<br/>";
});
$("#tdtitle").html(title);
$("#tdtype").html(type);
Terry, you wrote: "All that gives is an invalid character error on the line"? Then result is not a valid json. Test it here: http://jsonlint.com/, fix it, then try again.
var data = {
d:{
results: [
{ "Title": "apple", "Type": "rome", "State": null },
{ "Title": "grape", "Type": "fruit", "State": null }
]
}
};
var title = '';
var type = '';
$.each(data.d.results, function (index, value) {
title += "Title: " + value.Title + "<br/>";
type += "Type: " + value.Type + "<br/>";
});
alert(title + type);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

updating an existing item in an azure mobile service database

I have a server side script which is trying to update an already existing row with new data that is calculated in the script. When there isn't a row there it adds to the table fine.However when I try to update the row I get an error in my application that tells me that an item with that id already exists.
Below is the code I am using for the script. Any tips would be much appreciated.
function insert(item, user, request) {
var table = tables.getTable('Reviews');
table.where({
text: item.id
}).read({
success: upsertItem
});
function upsertItem(existingItems) {
if (existingItems.length == 0) {
item.numReviews = 1;
item.rating = item.reviews;
request.execute();
} else {
item.id = existingItems[0].id;
item.numReviews = existingItems[0].numReviews + 1;
var average = existingItems[0].reviews / item.numReviews;
item.reviews = existingItems[0].reviews + item.reviews;
item.rating = average;
table.update(item, {
success: function(updatedItem) {
request.respond(200, updatedItem)
}
});
}
}
}
For your initial query, you want to query by the id field:
table.where({
id: item.id
}).read({
success: upsertItem
});
Edit: further clarification
Your query object, {text: item.id} is effectively turned into the SQL query, select * from Reviews where text = item.id where item is the POST body. So your code sample is searching for Reviews where the text column has an id value in it. It doesn't find any, so the upsert() callback function if statement evaluates to true because existingItems is empty, and tries to insert the item by calling request.execute().
With the change I suggested, using {id: item.id}, becomes a query like
select * from Reviews where id = item.id so it will search for the Review with a matching id value in the id column.

Jquery: Autocomplete with label

I am trying to learn website development.
While learning autocomplete feature of jquery, I tried to put in the labels.
function autocomplete (data) {
var data = data.toString();
var availableTags = data.split(',');
var autocompleteData = [];
for (var i = 0; i < availableTags.length; i++){
autocompleteData[i] = {};
autocompleteData[i].label = i.toString();
autocompleteData[i].value = availableTags[i];
}
$("#tags").autocomplete({
source: autocompleteData,
select: function (event, ui) {
printautocomplete(event, ui)
}
});
};
The autocomplete[i].value is a valid string.
autocompleteData[0]
Object {label: 0, value: "Peter"}
However, I do not see any suggestions.
What is wrong with the way I am using the API?
The API says:
"Array: An array can be used for local data. There are two supported formats:
An array of strings: [ "Choice1", "Choice2" ]
OR An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]
The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label. "
Thank you.
$('#sidebarSearch').autocomplete(
{
source: function(query, result)
{
var query = $('#sidebarSearch').val ();
$.ajax(
{
url:"sidebarSearchFetch.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
result($.map(data, function(item)
{
return {
label: item.name,
value: item.usrId
};
}));
}
})
},
appendTo: "#sidebar-form"
});
I am skeptical of line 2 in your code (var data = String()data;) I would use: var data = data.toString();
But if you are sure that the autocompleteData elements do indeed have valid strings, then my best guess would be that perhaps you forgot to give the '#tags' id to your html entry field element.
Finally, if this is not it, to troubleshoot, I would try removing the select: option from the object you are passing to autocomplete() in the line that begins: $("#tags").autocomplete(... so that only the source options is passed.
Another thing to check out is when the code is being run. It is possible that a document.ready() function is needed to ensure that that when the autocomplete feature is added to the DOM element with the id '#tags', that the element has already been created.
The autocomplete works fine. Instead of completing "value", it completes "label".
So when I type in "1", it suggests "1", "10", "11", etc.
Autocomplete applying value not label to textbox answers how to change to to by-value.

Splitting a string into words has resulted in splitting into letters

I'm new to Javascript. I need to split a string of this format:
["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]
and create as options for select tag. I tried the below code
$.each(data, function (index, value) {
$('#bu_group').append($('<option/>', {
value: value,
text : value
}));
});
But I get strings split as letters.
What can I do to split the string to get options as
<option>Man1</option>
<option>SKC2</option>
Note : Some times this string may contain spaces as well.
If data is your string, then parse it from JSON to a JavaScript array of strings, then iterate over that:
var yourArray = JSON.parse(data);
$.each(yourArray, function(index, value) {
$('#bu_group').append($('<option/>', {
value: value,
text : value
}));
});
Try to pass the array first and then pass the translated array as the html string,
$('#bu_group').html($.map(JSON.parse(data),function(val,i){
return "<option value="+ val +">" + val + "</option>";
}));
DEMO
As data is actually coming from your server via ajax you can simply specify correct dataType.
Either
$.ajax({dataType: 'json', ...}).done(function(data){
//data will be parsed
});
Or
$.getJSON(url).done(function(data){
//data will be parsed
});
Or configure your server to return correct mime type (application/json)
if your data is
["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]
then there is no problem, so I think you have your data as :
'["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]'
which you must 'parse' it.
as you are using jQuery, one option is to parseJSON like this:
var parsed_array = $.parseJSON('["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]');
after doing that, you can successfully do :
$.each(parsed_array, function (index, value) {
$('#bu_group').append($('<option/>', {
value: value,
text : value
}));
});
If you have your data as
var data=["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]
then you can iterate this var, isn't it?
var data=["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"];
for(i=0;i<data.length;i++) {
$('#bu_group').append($('<option/>', {
value: data[i],
text : data[i]
}));
};
JSFiddle here

jQuery Validate Plugin: How can I add groups to a validator after its been initialized?

On our site we are using an embedded sign-up form from our ESP that uses the jQuery validate plugin. We are customizing the form a bit, adding a couple of custom fields (first name, last name) and we want them to be grouped so there is only one error message for both the fields.
Since the form's validator has already been initialized I need to add in a few things dynamically. The plugin provides the rules( "add", rules ) method to add in validation rules dynamically, although we are just using class names to do this anyhow. But there is no clear way to set the groups option after the validator has been initialized.
I've tried a few different things to accomplish this, but none some to be working:
var settings = $("#mc-embedded-subscribe-form").validate().settings;
$("#mc-embedded-subscribe-form").validate($.extend(settings, {
groups: {
username: "FNAME LNAME"
},
errorPlacement: function(error, element) {
if (element.attr("name") == "FNAME" || element.attr("name") == "LNAME") {
error.insertAfter("#username_group");
} else {
error.insertAfter(element);
}
}
}));
The errorPlacement function is added to the validator, but not the groups.
I've also tried setting the groups option explicitly, but that has no effect either.
$("#mc-embedded-subscribe-form").validate().settings.groups = { username: "FNAME LNAME" };
$("#mc-embedded-subscribe-form").validate().groups = { username: "FNAME LNAME" };
I'm completely stumped as how to accomplish this.
I recently faced the same problem and found a different solution.
The Scenario
We have a table which grows dynamically as users add (or delete) rows. Each new row contains several elements, and we want each rows's input elements to be in a single validation group--one per row--because we only want one error label for each row. Because the rows are added dynamically--well after we call $('#the-form').validate()--we needed a way to add a new group each time the user adds a row.
Our Solution
We hacked the validator object by directly modifying its groups member:
// on document ready:
validator = $('#the-form').validate({
groups: ...,
rules: ...,
messages: ...,
etc.
});
...
// later, when we need to add a new validation group:
validator.groups['first_name_row_5'] = 'full_name';
validator.groups['last_name_row_5'] = 'full_name';
Those last two lines are equivalent to
groups: {full_name: 'first_name_row5 last_name_row_5'}
in the validator options, but can be added after the initial call to validate().
It's a hack into the internals of jquery.validate, but it works (with jquery validate v1.9.0).
Finally, to directly answer the OP's question: instead of this:
$("#mc-embedded-subscribe-form").validate().groups = { username: "FNAME LNAME" };
try this:
var validator = $("#mc-embedded-subscribe-form").validate();
validator.groups['FNAME'] = 'username';
validator.groups['LNAME'] = 'username';
I was looking for a way to do this too and found a solution in the jQuery help forum: http://forum.jquery.com/topic/jquery-validate-defining-groups-dynamically
var getGroups = function() {
var result = {};
$('#myTable tr').each(function(i) {
var field1Name = $(this).find('.field1').attr('name');
if (field1Name != undefined) {
var field2Name = $(this).find('.field2').attr('name');
result['fieldPair_' + i] = field1Name + ' ' + field2Name;
}
});
return result;
}
$('#myForm').validate({ groups: getGroups() });
I tried every method I could find to dynamically add groups. The only one that worked for me was based on Ron's method above. I had a table that had rows that were dynamically added, each containing a number of fields.
// Names of fields within each table row that's dynamically added
var validateNames=["field1","field2","field3"];
// This function overwrites all validator groups and is called during each change of the table
function createGroups() {
var result = {};
// Create any static groups
result['date-dd'] = result['date-mm'] = result['date-yyyy'] = 'date';
// Create groups from dynamically added table rows
var i = 1;
jQuery("tr", "#table-id tbody").each(function() {
for (j = 0; j < validateNames.length; ++j) {
result[validateNames[j] + "-" + i] = 'fieldGroup_' + i;
}
i++;
});
validator.groups = result;
}
put one errorElement: "span" which is used to display error on desired place. where username_group encode within span tag
$("#mc-embedded-subscribe-form").validate($.extend(settings, {
groups: {
username: "FNAME LNAME" },
errorElement: "span" ,
errorPlacement: function(error, element) {
if (element.attr("name") == "FNAME" || element.attr("name") == "LNAME") {
error.insertAfter("#username_group");
} else {
error.insertAfter(element);
} } }));

Categories

Resources