I am using a WebGrid to allow CRUD on my database (using MVC and EF entities). The grid works and filters they way I want it to. There are two columns that use dropdowns to display a value tied to another table (Projects and People) and these both work well for edits/ updates. I am using JQuery for an add new row and want the new row to have select fields like the grid does (so that the user can just find the person by name instead of having to enter the ID for example). I am referencing this post from another similar question, but when I implement the code I get a syntax error that I'm having trouble understanding.
Here is my scripting on the view side that shows my failed attempt. I'm creating an array from the project repository (Text is the name of the project and Value is the ID field), and populating it with the model values: Model.Projects, and then in the add row function I want to loop through the array to add in the options.
<script type="text/javascript">
var ProjectArray = new Array();
#foreach (var proj in Model.projects)
{
#:ProjectArray.push(Text: "#proj.Text", Value: "#proj.Value");
}
</script>
<script type="text/javascript">
$(function ()
{
$('body').on("click", ".add", function () {
var SelectedProject = "#Model.ProjectID";
var newRow = $('.save').length;
console.log('newRow = ' + newRow);
if (newRow == 0) {
var index = "new"+$("#meetingList tbody tr").length + 1;
var ProjectID = "ProjectID_" + index;
var Date = "Date_" + index;
var Attendees = "Attendees_" + index;
var Phase = "Phase_" + index;
var PeopleID = "PeopleID_" + index;
var Save = "Save _" + index;
var Cancel = "Cancel_" + index;
var tr = '<tr class="alternate-row"><td><span> <input id="' + ProjectID + '" type="select"/></span></td>' +
#* This is where I use the array to add the options to the select box*#
ProjectArray.forEach(function (item) {
if (item.Value == SelectedProject) { '<option selected="selected" value="' + item.Value + '">' + item.Text + '</option>' }
else { '<option value="' + item.Value + '">' + item.Text + '</option>' }
+
});
---remaining script omitted----
'<td><span> <input id="' + PeopleID + '" type="text" /></span></td>' +
'<td><span> <input id="' + Date + '" type="date" /></span></td>' +
'<td><span> <input id="' + Attendees + '" type="text" /></span></td>' +
'<td><span> <input id="' + Phase + '" type="text" /></span></td>' +
'<td> SaveCancel</td>' +
'</tr>';
console.log(tr);
$("#meetingList tbody").append(tr);
}
});
I am not sure how to parse the error, but the page source looks like this when creating my client side array:
var ProjectArray = new Array();
ProjectArray.push(Text: "Select Project", Value: ""); //<-- ERROR HERE:
ProjectArray.push(Text: "010111.00", Value: "74");
ProjectArray.push(Text: "013138.00", Value: "2");
So the model getting into the client side works (the text and value pairs are correct), but the error I get is for the first array.push line: missing ) after the argument list. I have played with moving this code block around, putting it in a separate <script> tag and the error likewise follows it around, always on the first array.push line. And regardless of where it is, the rest of my script functions no longer work. I think it must be something silly but I just am not seeing what I'm doing wrong.
The option list does not populate into something I can ever see, it just renders out on the page source as the javascript loop:
var tr = '<tr class="alternate-row"><td><span> <input id="' + ProjectID + '" type="select"/></span></td>' +
ProjectArray.forEach(function (item) {
if (item.Value == SelectedProject) { '<option selected="selected" value="' + item.Value + '">' + item.Text + '</option>' }
else { '<option value="' + item.Value + '">' + item.Text + '</option>' }
+
}); //-- Unexpected token here
And with the push array in its separate script block I get a second error that the last } is an unexpected token. This is some javascripting error I'm sure. But where it is an how to do this are beyond me right now.
I'm not used to javascript, and poor syntax leads to the vague errors I was getting. The first problem was fixed by adding the { . . . } around the array values. Then I created a function to create the arrays I need for people and projects as well as a function to take an array and create the option list to clean up the view code:
function createProjectArray() {
var ProjectArray = new Array();
#foreach (var proj in Model.projects)
{
if (proj.Value != "") {
#:ProjectArray.push({ Text: "#proj.Text", Value: "#proj.Value" });
}
}
return ProjectArray;
}
function createPeopleArray() {
var PeopleArray = new Array();
#foreach (var person in Model.people)
{
if (person.Value != "") {
#:PeopleArray.push({ Text: "#person.Text", Value: "#person.Value" });
}
}
return PeopleArray;
}
function SelectOptionsString(MyArray, SelectedValue) {
console.log(MyArray);
var OptionsList = "";
MyArray.forEach(item => {
if (item.Value == SelectedValue) { OptionsList += '<option
selected="selected" value="' + item.Value + '">' + item.Text + '</option>'; }
else { OptionsList += '<option value="' + item.Value + '">' + item.Text
+ '</option>'; }
})
return OptionsList;
}
Taking this approach allowed me to more easily parse the code and find the syntax errors. The Array.forEach syntax was an interesting hurdle, and this site helped me test out my syntax to eventually get it working as above.
So the server creates the javascript lines to create the array, and then I use the array to create my dropdown options list. This cleans up the add row function code nicely:
$('body').on("click",".addrow", function() {
var SelectedProject = "#Model.ProjectID";
var ProjectArray = createProjectArray();
var ProjectOptions = "";
ProjectOptions = SelectOptionsString(ProjectArray, SelectedProject);
var PeopleArray = createPeopleArray();
var PeopleOptions = "";
PeopleOptions = SelectOptionsString(PeopleArray, "");
var tr = '<tr class="alternate-row"><td><span> <select id="' +
ProjectID + '>' + ProjectOptions + '</select></span></td>' +
'<td><span> <select id="' + PeopleID + '>' + PeopleOptions +
'</select></span></td>' + '</tr>'
$("#myWebGrid tbody").append(tr);
});
And it also allows for some potential code reuse.
Related
I am seeking help trying to add a new table in my third function called ingredients. I am not very familiar with javascript so I tried to duplicate code from newDosage which is similar to what I need to do. Unfortunately, right now all I see is 0, 1, or 2 and not the actual text from the ingredient table. If anyone can help me correctly call the table, it would be greatly appreciated. Thank you.
Below is my code. The first function pulls the database, the second function uses the results and the third function is where I have tried to add the ingredient table.
function listTreatmentDb(tx) {
var category = getUrlVars().category;
var mainsymptom = getUrlVars().mainsymptom;
var addsymptom = getUrlVars().addsymptom;
tx.executeSql('SELECT * FROM `Main Database` WHERE Category="' + category +
'" AND Main_Symptom="' + mainsymptom + '" AND Add_Symptom="' + addsymptom + '"',[],txSuccessListTreatment);
}
function txSuccessListTreatment(tx,results) {
var tubeDest = "#products";
var len = results.rows.length;
var treat;
for (var i=0; i < len; i = i + 1) {
treat = results.rows.item(i);
$("#warning").append("<li class='treatment'>" + treat.Tips + "</li>");
$("#warning-text").text(treat.Tips);
$('#warning').listview('refresh');
//console.log("Specialty Product #1: " + treat.Specialty1);
if(treat.Specialty1){
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, '1'));
}
if(treat.Specialty2){
$("#products").append(formatProductDisplay('specialty2', treat.Specialty2, treat.PurposeSpecialty2, treat.DosageSpecialty2, '0'));
}
}
}
function formatProductDisplay(type, productName, productPurpose, productDosage, Ingredients, aster){
var newDosage = productDosage.replace(/"\n"/g, "");
if(aster=='1'){ productHTML += "*" }
productHTML+= "</div>" +
"</div>" +
"<div class='productdose'><div class='label'>dosage:</div>" + newDosage + "</div>" +
"<div class='productdose'><div class='label'>ingredients:</div>" + Ingredients +
"</div></li>"
return productHTML;
}
You are missing an argument when you call formatProductDisplay(). You forgot to pass in treat.Ingredient.
Change:
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, '1'));
To:
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, treat.Ingredients, '1'));
Also do the same thing to the similar 'Specialty2' line right below it.
I am new to AJAX/JQuery/JSON, I am using Struts 2 to get a JSON object using AJAX, I can see the object returned but I am unable to iterate over it. The returned object is a list that has just one object(may contain more objects), also every object contains a list of some other object.
This is how the js file looks like:
$.getJSON('GetAllSaleItemsAction', {
customerName : debtorSelection
}, function(jsonResponse){
//alert(jsonResponse);
//populate table
var trHtml = '';
//$("tr:has(td)").remove();
jsonResponse = jsonResponse.saleItemsList;
var responseString = JSON.stringify(jsonResponse);
console.log(responseString);
$.each(jsonResponse, function(i, item) {
var saleEntries = $.parseJSON(item.singleSaleEntries);
var saleEntriesString = JSON.stringify(saleEntries);
console.log(saleEntriesString);
var sseString = '';
$.each(saleEntries, function(n, sse){
sseString += sse.item + ' ' + sse.quantity + ' x ' + sse.price + ' = ' + sse.amount;
});
trHtml+= '<tr><td>' + item.date + '</td><td>' + sseString + '</td><td>' + item.saleAmount + '</td><td>' + item.interest + '</td><td>' + item.totalAmount + '</td></tr>';
});
if(trHtml != ''){
$('#saleRecordTable').append(trHtml);
}
});
Here the first console.log is executed but not the second console.log as javascript inside the each-function is not executed:
[{"customerName":"Tester","date":"2015-02-16T17:36:19","debtorId":1,"interest":0,"saleAmount":14000,"saleId":3,"singleSaleEntries":[{"amount":9000,"item":"DAP_50KG","price":900,"quantity":10,"saleEntry":null,"singleSaleId":4},{"amount":5000,"item":"UREA_50KG","price":500,"quantity":10,"saleEntry":null,"singleSaleId":5}],"totalAmount":14000}]
Please guide me.
The issue was with var saleEntries = $.parseJSON(item.singleSaleEntries);
After changing this statement to var saleEntries = item.singleSaleEntries;
everything works fine, the problem was that the debug point was set to next statement and because of error in this line, the control was never reaching there.
I need to build my DDL dynamically,I get info from DB using JSON (I get the data with no problem) but couldn't show my data in my DDL...
I tried three different ways, nothing changed.. What am I doing wrong ?
//HTML
<asp:DropDownList ID="productDDL" runat="server" CssClass="ddl"></asp:DropDownList>
//Javascript
function creatDDL(data) {
var obj = $.parseJSON(data.Data);
for (var i = 0; i < obj.length; i++) {
$("#productDDL").append("<option>" + obj[i].id + "' - '" + obj[i].name + "</option>");
$("#productDDL").append("<option>"+obj[i].id + "' - '" + obj[i].name+"</option>");
$("#productDDL").append($("<option></option>").html(obj[i].id + "' - '" + obj[i].name));
}
}
I like your third attempt best. Assuming your data is in order, you just need to brush up on the jQuery API.
Here's a working version of what I gather you're trying to do:
function createDDL(data) {
var options = $.parseJSON(data.Data);
$.each(options, function(n, option) {
var $option = $('<option />').text(option.name).val(option.id);
$("#productDDL").append($option);
});
}
Fiddle: http://jsfiddle.net/klenwell/Esr5q/
I have a Javascript function that prints various information from a json file and displays it in a table of contents fashion. It parses the information and prints it into a "ui-grid-b" div because i want them in rows of 3. I had a problem with the javascript printing repeatedly every time the page was opened so I added in a function to clear the div every time it prints. However, when I open a new seperate page with a "ui-grid-b" div in it it clears that and prints the table of contents again. Here's the js code and I hope you can help:
<script type="text/javascript">
var grid= new Array();
grid[0]= "a";
grid[1]= "b";
grid[2]= "c";
var j=0;
var color= new Array();
color[0]= '#00c6c4;';
color[1]= '#6fc41b;';
color[2]= '#ffbd0c;';
color[3]= '#ff84f1;';
color[4]= '#1fbbff;';
color[5]= '#ff1700;';
color[6]= '#976833;';
var k=0;
$(document).on("pageinit", "#Page1", function(){
var imp= "Json/empirical.json";
$.getJSON(imp, function(data) {
j=0;
k=0;
var toc= '';
$.each(data.tcontent, function(index, item) {
if (j > 2) { j = 0; }
if (k > 6) { k = 0; }
toc += "<div class='ui-block- ' " + grid[j] + " '>" + item.url + '<div class="grid" style="background-color: ' + color[k] + ' ">' + "<p class='gridtext'>" + item.Name + "</p>" + "</div>" + "</a>" + "</div>"
j++;
k++;
});
$(".ui-grid-b").empty().append(toc);
});
});
</script>
Assign your toc grid a unique ID:
<div id="theTOC" class="ui-grid-b"></div>
Then in your code instead of:
$(".ui-grid-b").empty().append(toc);
do
$("#theTOC").empty().append(toc);
Make sure this id is unique accross all pages. Also make sure your pages have unique IDs (i.e. only one page called "Page1").
I create a <select> menu using Javascript then attach it to the page. But when I click on it, it closes immediately.
Here's my code, I'm stumpped.
var accounts = [
['user1', 'password'],
['user2', 'passowrd']
]
function html(){
var button = 'Switch User • ';
$('a[href=search.php]')[0].before(button);
$('#switchacc').click(function(){
$(this).html('<select id="accounts">'+ accountss +'</select>');
return false;
});
var accountss = '';
for(i = 0; i <= accounts.length; i++){
accountss = accountss + '<option name="' + accounts[i][0] + '" value="' + i + '">' + accounts[i][0] + '</option>';
}
}
html();
Why are you embedding your select in that a link? See this fiddle for an example. You cannot embed a list in a link.