We are using fullcalendar with .netcore-razor pages. We can made crud operaitons in calendar.
We got users and they have property with userColor:'#hex_color'. So I want to add dots in calender for each user color.
This is the calendar
This is the type I want
Basicly i just want to add dots for each event with dot color=user color
$.each(data, function(i, v) {
console.log(v);
events.push({
id: v.id,
title: v.subject,
tooltitle: v.tool,
description: v.description,
start: moment(v.start),
end: v.end != null ? moment(v.end) : null,
color: v.themeColor,
allDay: v.isFullDay,
type: v.type,
rate: v.rate,
status: v.status,
//HERE
textColor: v.TextColor
});
})
in creating calendar
$('#calender').fullCalendar({
contentHeight: 1000,
eventLimit: true,
eventColor: '#394006',
events: events,
//...
Or can I make it in controller. How can i give style in there
foreach (var user in item.Users)
{
//var user = _userManager.FindByIdAsync(id).Result;
//here's the data
usertxt += user.Name+" "+user.Surname + " ● ";
usertxt2 += user.Name+" "+user.Surname + " <br> ";
//New try is
var v = HttpUtility.HtmlDecode("<span style='background: Red; width:15px; height:15px; radius: 100 %;'></span> ");
usertxt += user.Name + " " + user.Surname + v;
//It turns into in developer view
demo user1 <span style='background: Red; width:15px; height:15px; radius: 100 %;'></span> demo user2<span style='background: Red; width:15px; height:15px; radius: 100 %;'></span>
//But now shows any dot beacuse edit as hmtl codes are
<span class="fc-title">Demo user<span style='background: Red;'>●</span> <span style='background: Red;'>●</span> <span style='background: Red;'>●</span> Demo <span style='background: Red;'>●</span> </span>
< and > turns into lt, gt
Finally !! it works with that way but When Date changes. The render is gone. How can make it rerender
I want to rerender it when date changes
//also in evenrender same code
//eventRender: function (event, element) {
var titles = JSON.parse(test);
if (!jQuery.isEmptyObject(titles)) {
$(".id_" + event.id + " .fc-title").append('<br>');
$.each(titles.User, function (k, titlee) {
var span = document.createElement('span');
span.style.color = titlee.User_Color;
span.innerHTML = "●";
$(".id_" + event.id + " .fc-title").append(span);
console.log("TEST");
});
}
It would make a lot more sense if your user data was part of your event object, so that each event has a list of the users associated with it, and what colour should be used for them.
And you can append the dot to the title area of the event, to avoid it being placed on the next line.
eventRender: function (event, element) {
var title = $(element).find(".fc-title");
event.users.forEach(function(user) {
var span = document.createElement("span");
span.style.color = user.color;
span.innerHTML = " ●";
title.append(span);
});
}
This is based on an event which has a property "users" as part of it, structured like this:
users: [{ "color": "red" }, { "color": "blue" }]
Demo: https://codepen.io/ADyson82/pen/MWjwBBJ?editable=true&editors=001
Related
I'm getting JSON data from the API, like this
data = {
q: 'sugar',
from: 0,
to: 10,
params: {
sane: [],
q: [ 'sugar' ]
},
more: true,
count: 1000,
hits: [{
recipe: {
uri: 'http://www.edamam.com/ontologies/edamam.owl#recipe_a46ae0ad4f8320fa6285b25fc7b36432',
label: 'Bread Pudding with Apple and Brown Sugared Bacon',
image: 'https://www.edamam.com/web-img/1ae/1ae111af3737d42e9d743445f5605373.JPG '
},
recipe: {
uri: 'http://www.edamam.com/ontologies/edamam.owl#recipe_a36b51f50f102bf5da228af55d2ce040',
label: 'Vanilla sugar',
image: 'https://www.edamam.com/web-img/4fd/4fdd2336043aa81dd05a4b6a08934402.jpg',
}
}]
}
And I try to bind the recipe to divs. For example, there is a div with the id columns,
Here is that piece of codes.
var list = data.hits;
function Builddivs(list) {
var array = new Array(0);
var count = list.length;
for (var i = 0; i < 10; i++) {
var p = list[i];
title = p.recipe.label;
imgurl = p.recipe.image;
href = p.recipe.url;
array.push("<div class='pin'><a href='" + href + "'><img src='" + imgurl + "'/></a><p>" + title + "</p> </div>");
}
var html = array.join("");
$("#columns").html(html);
}
The problem is to generate that html takes like several seconds, so is there a better way to do that? like bind the data directly to existing dynamic number of divs? Thanks!
Instead of generating a lot of HTML at once, it would be more efficient to edit existing HTML.
Example jsfiddle solution to this question
Editing HTML with jQuery
You can replace or add text or HTML to a div:
$(selector).html('Try <span class="red">this!</span>');
$(selector).text('Just add some text');
$(selector).append('Some HTML');
Adding src to an image or adding href to a link:
$(selector).attr('src','http://example.com/someimage.jpg');
$(selector).attr('href','http://example.com');
Instead of using a for loop, you could use javascript Array.forEach or jquery $.each
Generating HTML for the first time
On every run (every time the list changes) you can check if the HTML element to be edited exists. If not, then you can generate the appropriate HTML. On the first run of the code, the HTML would then be generated for every element from the list.
See this question to see how to check if elements exist:
How do you check if a selector matches something in jQuery?
Example
Here is a working jsfiddle with an example of how HTML can be edited using $().attr and $().html: https://jsfiddle.net/fyux250p/1/
var hitsContent =""
(list || []).forEach(function(data,index){
hitsContent += "<div class='pin'><a href='" + data.url + "'><img src='" + data.url + "'/></a><p>" + data.label + "</p> </div>";
})
$("#columns").html(hitsContent);
I've been scratching my head since long time, but unable to get any resolution for this. In a twitter bootstrap theme, I've written this function to recursively build the navigation menus. For the time being, I've put the menu structure in a list containing JSON objects, but ultimately it will be fetched dynamically. Here is the code that does this:
function createMenus() {
//fill the menus in navbar dynamically.
vars={};
vars.title = "RAFinder";
vars.menus = ['Home',
{'Student':['Search Jobs','Sent Applications', 'Find Professors', 'My Profile', 'Test Scores']},
{'Professor':[
{'Research Jobs':['Research Jobs', 'Search RA', 'Sent Applications', 'Find Students', 'Student Profiles', 'Students Past Jobs and Performance', 'My Profile']},
{'Posted Jobs':['Contracts FixedHourly', 'Work Diary', 'Reviewevaluation of students performance']},
{'Messages':['Inbox', 'Sent', 'Archive']},
]},
'About','Contact'
];
//$('#divmain').html('');
for (var i=0;i<vars.menus.length;i++)
populateMenu(vars.menus[i]);
$('title').text(vars.title);
$('.navbar-brand').text(vars.title);
}
As you can see the structure is composed of list of items that can be either String (for menus) or JSON objects (for sub-menus to recurse further). Here is the populateMenu that recursively does this:
function populateMenu(menu, parent='') {
console.log(menu, parent);
tp=type(menu);
if (tp=="string")
{
//Just fill menu.
$('#divmain').append(parent + '::' + menu + '<br>');
addMenuItem(menu, parent, false); //actually add it on bootstrap navbar
}
else if (tp=="object")
{
$('#divmain').append('Length of dict is: ' + Object.keys(menu).length.toString() + '<br>');
k='';
for (var key in menu) //this should ideally be one loop
{
//if (menu.hasOwnProperty(k)) {
// }
console.log('ITERATING::',key);
k = key;
}
//else {$('#divmain').append('notOwnProperty: ' + k);}
//just fill k
$('#divmain').append(parent + '::' + k.toString() + '-><br>');
addMenuItem(k.toString(), parent, true); //actually add it on bootstrap navbar
l = menu[k];
//for(item in l)
for(var i=0;i<l.length;i++)
{
//$('#divmain').append(k + '::' + l[item] + '-><br>');
$('#divmain').append('Now calling populateMenu for dict ' + l[i].toString() + ' and parentIs: ' + k.toString() + '<br>');
populateMenu(l[i], k.toString()); //these are dropdowns
}
}
}
The root level menus are filled okay (i.e. Home, Student, Professor, About, Contact). Even the Student sub-menus are filled okay. The trouble is with the Professor sub-menus. Only the first JSON object in the list which is "Research Jobs" is filled. The rest are just ignored by the for loop, I don't understand why.
Finally, I solved this in the following manner:
function createMenus() {
//fill the menus in navbar dynamically.
vars.menus = ['Home',
{'Student':['Search Jobs','Sent Applications', 'My Profile']},
{'Professor':[
{'Research Jobs':['Search RA', 'Sent Applications', 'Find Students', 'Student Profiles', 'Students Past Jobs and Performance']},
{'Posted Jobs':['Contracts FixedHourly', 'Work Diary', 'Review/Evaluation of students performance']},
{'Messages':['Inbox', 'Sent', 'Archive']},
]},
'About','Contact'
];
buildMenu(vars.menus, $('.navbar-nav'));
}
function buildMenu(arr, parentEl) {
arr.forEach(function(root) {
var li;
var id;
// This is a normal string entry
if ( typeof root === 'string' ) {
id = root;
li = $('<li></li>').html('' + root + '');
parentEl.append(li);
}
// Or this is an object
else {
// Loop over all the keys
Object.keys(root).forEach(function(child) {
id = removeSpecialChars(child);
istopmenu = parentEl.hasClass('navbar-nav');
li = $('<li class="dropdown' + (istopmenu ? '' : ' dropdown-submenu') + '"></li>').html('<a class="dropdown-toggle" data-toggle="dropdown" href="#" onclick="javascript:createView(\'' + id + '\');" aria-expanded="false">' + child + (istopmenu ? '<span class="caret"></span>' : '') + '</a>');
var ul = $('<ul class="dropdown-menu" role="menu"></ul>');
// Recursively loop over the array elements
buildMenu(root[child], ul);
li.append(ul);
parentEl.append(li);
});
}
});
}
I'm using JavaScript/jQuery. I'm having an issue with looping through an array to display the data as well as removing contents via button clicks.
Original Code in Question
HTML
<textarea id="sds">Apple
Banana
Grape
Orange</textarea>
<input type="hidden" id="sdh" />
Problem: Every button returns 5!
<div id="popup" title="Poof">
</div>
Script
var sds = $("#sds").val();
var sda = sds.split("\n");
var sdi = "";
$.each(sda, function(k, s) {
sdi += "<input type='text' id='sd" + k + "' value='" + s + "' /><button id='button" + k + "'>Click Me</button><br />";
$("#sdh").val(k);
});
$("#popup").html(sdi);
var h = $("#sdh").val();
var i = 0;
while (i <= h) {
$("#button" + i).click(function() {
// Here is where I have a problem trying to manipulate the input associated to the button.
alert(i); // Test to see what returns for the value of i.
$("#sd" + i).val("Clicked button " + i);
});
i++;
}
CSS (Thanks for providing the CSS to make the demo look better, Jose!)
#sds {
display: none;
}
jsFiddle
Revised Code
HTML
<textarea rows="4" cols="40" id="sds">Apple
Banana
Grape
Orange</textarea>
<input type="text" id="sd" value="Click here to verify" />
<input type="hidden" id="key" />
<div id="popup" title="Verify Multiple Fruits">
</div>
Script
$(document).ready(function() {
var sds = $("#sds").val();
var sda = sds.split("\n");
var sdi = "";
$.each(sda, function(key, sd) {
sdi += "<input type='text' id='sd" + key + "' value='" + sd + "' /><button id='button'" + key + "'>Remove</button><br />";
alert(key); // Test to see what returns for the value of i.
$("#button" + key).click(function() {
// Here is where I have a problem trying to manipulate the input associated to the button.
$("#sd" + key).val("Clicked button " + i);
});
$("#key").val(key);
});
$("#popup").html(sdi);
});
$(function() {
$("#popup").dialog({
autoOpen: false,
buttons: {
"Update": function() {
var key = $("#key").val();
var i = 0;
var sds = "";
while (i <= key) {
sds += $("#sd" + i).val() + "\n";
i++;
}
sds = sds.slice(0, -1);
$("#sds").val(sds);
$(this).dialog("close");
},
"Cancel": function() {
$(this).dialog("close");
}
},
close: function() {
},
height: 320,
hide: {
duration: 1000,
effect: "explode"
},
modal: true,
resizable: false,
show: {
duration: 1000,
effect: "blind"
},
width: 480
});
$("#sd").focus(function() {
$("#popup").dialog("open");
});
});
CSS (Thanks again for the CSS here, Jose!)
#sds {
display: none;
}
#popup input,
#popup button {
float: left;
width: auto;
}
#popup input {
clear: left;
}
jsFiddle
Revised Code after Applying One of the Answers
HTML
<textarea rows="4" cols="40" id="sds">Apple
Banana
Grape
Orange
Pear
Strawberry</textarea>
<input type="text" id="sd" value="Click here to verify." />
<input type="hidden" id="key" />
<div id="popup" title="Verify Multiple Fruits"></div>
Script
$(document).ready(function() {
$.each($("#sds").val().split("\n"), function(key, sd) {
$("#popup").append(
$("<input type='text' id='sd" + key + "' value='" + sd + "' />").add(
$("<button id='button" + key + "'>Remove</button><br />").click(function() {
$("#sd" + key).val("");
$("key").val(key);
})));
});
});
$(function() {
$("#popup").dialog({
autoOpen: false,
buttons: {
"Update": function() {
var key = $("#key").val();
var i = 0;
var sds = "";
while (i <= key) {
sds += $("#sd" + i).val() + "\n";
i++;
}
sds = sds.slice(0, -1);
$("#sds").val(sds);
$(this).dialog("close");
},
"Cancel": function() {
$(this).dialog("close");
}
},
close: function() {
},
height: 320,
hide: {
duration: 1000,
effect: "explode"
},
modal: true,
resizable: false,
show: {
duration: 1000,
effect: "blind"
},
width: 480
});
$("#sd").focus(function() {
$("#popup").dialog("open");
});
});
CSS (This is really awesome, Jose!)
#sds {
display: none;
}
#popup input,
#popup button {
float: left;
width: auto;
}
#popup input {
clear: left;
}
jsFiddle
Suppose the value of sds is Apple, Banana, Grape and Orange on different lines. Each button created by the .each() loop will have the correct number assigned, but when trying to change the value, the variable i returns 5 on the alert message box while the next line doesn't seem to work at all - due to the index being off.
How can I revise this code to make it work like it's supposed to?
Corrected the error mentioned by the loving and caring commentators. Still not working. Obviously that wasn't the issue as my original code that I copied off of had the parenthesis closed correctly. I was hand-jamming the code here since I have no ability to copy and paste the code here, so a small typo was made. My question is about the logic, not typo. Thanks!
In order to minimize the confusion, I've revised the code section of this question to reflect the original code I had, so it'll show the consistency with the answers Jose provided below.
Obviously, the revised code also had more issues, so I made a new revision yet again. Here is what I've gotten so far. It's still quirky, but works on most part. I'm going to need help with the cancel action on the modal dialog since it won't bring back the previous values from the textarea tag. Also, please, note the version changes on jQuery and addition of jQuery UI to the JSFiddle demo to reflect my development environment.
The Ultimate Solution
HTML
<textarea rows="4" cols="40" id="sds">Apple
Banana
Grape
Orange
Pear
Strawberry</textarea>
<input type="text" id="sd" value="Click here to verify." />
<div id="popup" title="Verify Multiple Fruits"></div>
Script
$(document).ready(function() {
if ($("#sds").val()) {
var i = 0;
$.each($("#sds").val().split("\n"), function(key, sd) {
$("#popup").append(
$("<input type='text' class='blah' id='sd" + key + "' value='" + sd + "' />").add(
$("<button id='button" + key + "'>Remove</button><br />").click(function() {
$("#sd" + key).val("");
})));
i++;
window["i"] = i;
});
}
});
$(function() {
$("#popup").dialog({
autoOpen: false,
buttons: {
"Update": function() {
var i = window["i"];
var sds = "";
$(".blah").each(function(i) {
if ($(this).val()) {
sds += $("#sd" + i).val() + "\n";
}
});
sds = sds.slice(0, -1);
$("#sds").val(sds);
$(this).dialog("close");
},
"Cancel": function() {
$(this).dialog("close");
}
},
close: function() {
$("#popup").html("");
if ($("#sds").val()) {
var i = 0;
$.each($("#sds").val().split("\n"), function(key, sd) {
$("#popup").append(
$("<input type='text' class='blah' id='sd" + key + "' value='" + sd + "' />").add(
$("<button id='button" + key + "'>Remove</button><br />").click(function() {
$("#sd" + key).val("");
})));
i++;
window["i"] = i;
});
}
},
height: 320,
hide: {
duration: 1000,
effect: "explode"
},
modal: true,
resizable: false,
show: {
duration: 1000,
effect: "blind"
},
width: 480
});
$("#sd").focus(function() {
if ($("#sds").val()) {
$("#popup").dialog("open");
}
});
});
CSS
#sds {
display: none;
}
#popup input,
#popup button {
float: left;
width: auto;
}
#popup input {
clear: left;
}
jsFiddle
Thoughts after Solving the Issue
I was initially irritated by the people who pointed out the typos rather than trying to see the entire picture to discover the "big" flaw with the program itself because that's what I thought I would have done for people who would ask me for guidance. Then, it hit me when I thought about how I would really react when I see petty mistakes like typos and bad grammars. I admit I hate seeing those petty mistakes, mostly because I have an obsessive-compulsive disorder when it comes to writing anything, including codes. Now that I've learned about JSFiddle, I'll test my code there before trying to post a question here from now on. It has been a terrific learning experience and thanks to all for the assistance.
There are several ways to solve this problem.
Use a closure
Inside the loop, declare an anonymous function and call it immediately, passing in i as the parameter local_i. In other words, i has a global scope, but the local_i has a scope limited to the anonymous function. This way, the click event "sees" the local_i value, not the i (5) as you had before.
while (i <= h) {
(function (local_i) {
$("#button" + local_i).click(function() {
alert(local_i); // Test to see what returns for the value of i.
$("#sd" + local_i).val("Clicked button " + local_i);
});
})(i); // <-- HERE I am calling the function
i++;
}
Click here for a live demo
Get the index from the button id
There is one pattern here: You want i=0 for #button0, i=1 for #button1.
So, just get the index from the id. This solution requires no loops.
// select all buttons inside #popup, that have an id starting by "button"
$("#popup button[id^=button]").click(function() {
var i = parseInt($(this).attr('id').replace('button', ''));
alert(i); // Test to see what returns for the value of i.
$("#sd" + i).val("Clicked button " + i);
});
Live demo
Optimized version, no loops, no global variables
$.each($("#sds").val().split("\n"), function(k, s) {
$("#popup").append(
// append the text box
$("<input type='text' id='sd" + k + "' value='" + s + "' />").add(
// and the button with the click already defined
$("<button id='button" + k + "'>Click Me</button>").click(function() {
alert(k);
$("#sd" + k).val("Clicked button " + k);
}))
);
});
Live demo
Final Solution
Brand new code was pasted into the question. To fix the problem in that code, just change
$("#button" + key).click(function() {
// Here is where I have a problem trying to manipulate the input associated to the button.
$("#sd" + key).val("Clicked button " + i);
});
to
$("#button" + key).click(function() {
var i = $(this).attr('id').replace('button', '');
$("#sd" + i).val("Clicked button " + i);
});
You can use the other alternatives I wrote above.
Hope this helps.
you have an error here
$("#button" + i.click(function() {
it should be
$("#button" + i).click(function() {
corrent that and it will work.
I am going to do the best I can explaining what I am trying to do here. Its a bit complex(for me at least)
I currently have an object that I loop through and populate an html form with inputs dynamically. This code places the object values in the inputs and allows me to edit/save them back to the object.
What I need to do however, is actually map the object fields to a set of fields that are defined in another object. The reason for this is that the original Object sometimes is missing data and I would like to add it from my form.
For example: My object has a property 'Button'. And the object has k,v for lets say width, height, and position. But in my other Object which defines available fields for 'Button' has width, height, position, color, and transition. What I am trying to do is, when I click on 'Button' label(see my demo) it shows me all the fields in my 'Controls' object and fills in all the values from my other Object which contains the values. I can then add values into the inputs that are empty and it will save them back to my Object.
Here is my Demo(click on the labels to see the form inputs): http://jsfiddle.net/bGxFC/6/
Here is my code:
var controls = {
"Controls": [{
"Button":[{"Transition": "","BackgroundImage": "","Position": "","Width": "","Height": ""}],
"Image":[{"BackgroundImage": "","Position": "","Width": "","Height": "", "Type": ""}],
"Label":[{"Position": "","Width": "","Height": "","Text": "","FontSize":"","Color": "", "FontType": ""}]
}]
};
var str = 'View\n{\n Image\n {\n BackgroundImage: Image.gif;\n Position: 0, 0;\n Width: 320;\n Height: 480;\n }\n\n Button\n {\n BackgroundImage: Button.gif;\n Transition: View2;\n Position: 49, 80;\n Width: 216;\n Height: 71;\n }\n\n Button\n {\n BackgroundImage: Button2.gif;\n Position: 65, 217;\n Width: 188;\n Height: 134;\n }\n\n Label\n {\n Position: 106, 91;\n Width: 96;\n Height: 34;\n Text: "Button";\n FontSize: 32;\n Color: 0.12549, 0.298039, 0.364706, 1;\n }\n \n\n}';
str = str.replace(/(\w+)\s*\{/g, "$1:{"); // add in colon after each named object
str = str.replace(/\}(\s*\w)/g, "},$1"); // add comma before each new named object
str = str.replace(/;/g, ","); // swap out semicolons with commas
str = str.replace(/,(\s+\})/g, "$1"); // get rid of trailing commas
str = str.replace(/([\d\.]+(, [\d\.]+)+)/g, "[$1]"); // create number arrays
str = str.replace(/"/g, ""); // get rid of all double quotes
str = str.replace(/:\s+([^\[\d\{][^,]+)/g, ':"$1"'); // create strings
$("#parseList").html(str);
var objStr;
eval("objStr={" + str + "};");
//End Parse String
$(document).ready(function () {
var $objectList = $('<div id="main" />').appendTo($('#main'));
$.each(objStr.View, function(k, v) {
$('<div/>').append(k).appendTo($objectList).on('click', function(){
var $wrapper = $('#form .wrapper').empty();
if(typeof v === 'string') {
$('<div class="item" />').append('<span class="key">' + k + '</span>' + '<input value="' + v + '"/>').appendTo($wrapper);
}
else {//object
$('<h3 class="formHeading" />').append(k).appendTo($wrapper);
$.each(v, function(key, val) {
$('<div class="item" />').append('<span class="key">' + key + '</span>' + '<input value="' + val + '"/>').appendTo($wrapper);
});
}
$("<button>Save</button>").appendTo($wrapper).on('click', function() {
if(typeof v === 'string') {
v = $(this).closest(".wrapper").find("input").val();
}
else {//object
$(this).closest(".wrapper").find(".item").each(function(i, div) {
var $div = $(div),
key = $div.find(".key").text(),
val = $div.find("input").val();
v[key] = val;
});
}
});
});
});
});
How would I solve this problem?
You need the input elements in html to contain the object keys they associate too.
Something like:
<div class="wrapper">
<h3 class="formHeading" data-item="Button_2">Button_2</h3>
<div class="item"><span class="key">Type</span><input value="Button" data-property="Type"></div>
<div class="item"><span class="key">BackgroundImage</span><input value="Button2.gif" data-property="BackgroundImage"></div>
<div class="item"><span class="key">Position</span><input value="65,217"></div><button class="save">Save</button>
</div>
JS
$('button.save').click(function(){
var $form=$(this).closest( '.wrapper'), itemName=$form.find('.formHeading').data('item')
var objectItem= storedObject[ itemName ];
$('.item').each(function(){
var $input=$(this).find(':input');
objectItem[ $input.data('property')]= $input.val();
})
})
If you can get rid of all of the string parser and use a proper javascript object in a demo, and add these html modifications I will be happy to help debug from there
I have two divs and a link for each. I'm trying to write an onclick function that appends a new div inside one of the two divs. The new div will have two form inputs appended to them. The new div will have a timestamp unique id tag. I suck at javascript and can't figure out what i'm doing wrong though.
Heres a link to a jsfiddle i'm trying to work on it with http://jsfiddle.net/XLuHU/6/
<a href='javascript:void;' onclick='return add_item("xyz", "Candy", "45.99", "#item_box1")'>Add Item to Box 1</a>
<br>
<a href='javascript:void;' onclick='return add_item("123", "Soda", "1.99", "#item_box2")'>Add Item to Box 2</a><br><br>
<div id='item_box1'></div><br><br>
<div id='item_box2'></div>
function add_item(code, title, price, divbox){
var idtag = "div_" + event.timeStamp;
if(divbox == "#item_box1")
{
var item_title = $("<input/>", {
type: 'text',
name: "box1_item_title[]",
value: title,
});
var item_price = $("<input/>", {
type: 'text',
name: "box1_item_price[]",
value: price,
});
var new_item = item_title + " - " + item_price;
}
else
{
var item_code = $("<input/>", {
type: 'text',
name: "box2_item_code[]",
value: code,
});
var item_title = $("<input/>", {
type: 'text',
name: "box2_item_title[]",
value: title,
});
var new_item = item_code + " - " + item_title;
}
$(divbox).append("<div id='"+idtag+"' ></div>");
$("#"+idtag).append(new_item);
};
First off this line is incorrect, event is not defined in this context:
var idtag = "div_" + event.timeStamp;
This might work better:
var idtag = "div_" + new Date().getTime();
Also this line will produce the wrong expected outcome, since your adding two objects together:
var new_item = item_title + " - " + item_price;
Also you have trailing commas in your object, which should have caused JS error, but didn't seem to in the latest version of Chrome and Firefox.
Here is the working fiddle, which is aslightly modified version of the code below, due to the fact that 'onclick="return add_item...' doesn't seem to work in JSFiddle. It just give "add_item" is undefined.
However, something like this should work in a normal HTML document:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#item_box1{
width: 300px;
margin: 0 auto;
height: 100px;
border: 1px solid blue
}
#item_box2{
width: 300px;
margin: 0 auto;
height: 100px;
border: 1px solid red
}
.link-button {
color: rgb(0, 0, 255);
cursor: pointer
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.3.js"></script>
<script type="text/javascript">
function add_item( code, title, price, divbox )
{
var idtag, item_title, item_price, item_code;
// Generate an id based on timestamp
idtag = "div_" + new Date().getTime();
// Generate a new div.
$( divbox ).append( "<div id=\"" + idtag + "\"></div>" );
if ( divbox == "#item_box1" )
{
item_title = $("<input/>", {
type: 'text',
name: "box1_item_title[]",
value: title
});
item_price = $("<input/>", {
type: 'text',
name: "box1_item_price[]",
value: price
});
// Show in the document.
$( "#" + idtag ).append( item_title, item_price );
}
else
{
item_code = $("<input/>", {
type: 'text',
name: "box2_item_code[]",
value: code
});
item_title = $("<input/>", {
type: 'text',
name: "box2_item_title[]",
value: title
});
// Show in the document.
$( "#" + idtag ).append( item_code, item_title );
}
}
</script>
</head>
<body>
<a class="link-button" onclick="return add_item('xyz', 'Candy', '45.99', '#item_box1');">Add Item to Box 1</a>
<br>
<a class="link-button" onclick="return add_item('123', 'Soda', '1.99', '#item_box2');">Add Item to Box 2</a>
<br>
<br>
<div id='item_box1'></div>
<div id='item_box2'></div>
</body>
</html>