dynamically add inputs via javascript - javascript

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>

Related

.net Core Fullcalendar show dots

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

on change after append new select2

I am using select2 and I want to handle on change event
it works well the first time, but when I append new select2 after every change and after appending new select2 on change does not work
$('select').on("select2:select", function(e) {
e.preventDefault();
var item_id = $("option:selected").data('id');
var product_id = $("option:selected").data('product');
$.ajax({
type: "post",
url: window.location.origin + '/product/get-items',
data: {
item_id: item_id,
product_id: product_id,
"_token": $('#csrf-token')[0].content //pass the CSRF_TOKEN()
},
success: function(data) {
$(".all-items").hide();
data.specifications.forEach(myFunction);
function myFunction(specification, index) {
var a = '<div class="all-items"><div class="mb-1"><div class="row py-1"><label style="font-size: 16px; margin: 10px; margin-bottom: 10px" class="py-1 mt-2">' + specification.name + ' :</label></div><div class="row"><select class="js-example-basic-single select-' + index + ' test' + index + ' item selectpicker selectItem" name="specification[]"> </div></div></div>';
$(".all").append(a);
specification.items.forEach(test);
function test(value, inx) {
if (data.itemIds.includes(value.id.toString())) {
var a = '<option style="font-size: 10px" data-id="e" data-product="dd" value="dd">' + value.name + '<span></span></option></select>';
$(".test" + index).append(a).select2();
}
}
}
}
});
});
I have to section for appending
first, append select2 and after this append options of each select
I want to use on change event for all select2 ( appending and initial )
the query selector $('select') collects only the current select elements in a document and not contains later elements appended to the document. So you need to use a more general selector to cover late elements. This should work:
$(document).on("select2:select","select",function(e) { })

Store object in div and retrieve via Jquery

I need to store a Javascript object into a div (or in production: many divs). It really needs to go into the data-object="" attribute – i don't want to add it later via $('div').data('object').
The below code only returns "{"... I feel like I have tried every combination of stringify and parse and whatnot.
Does anybody have a clue how to retrieve my object?
var Module = {
div: function() {
var object = {
name: 'one',
type: 'two'
};
var html = '<div data-object="' + JSON.stringify(object) + '"></div>';
var div = $(html).appendTo('body');
// This just returns "{" instead of my object
console.log(div.data('object'));
}
}
$(document).click(function() {
Module.div();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This is because JSON gets encoded using double quotes ", and you also encapsulate it between double quotes. The problem with this is that it produces :
<div data-object="{" name":"one","type":"two"}"></div>
so, when you read data-object, its value is effectively "{".
Try encapsulating it into simple quotes :
var Module = {
div: function() {
var object = {
name: 'one',
type: 'two'
};
var html = "<div data-object='" + JSON.stringify(object) + "'></div>";
var div = $(html).appendTo('body');
// This just returns "{" instead of my object
console.log(div.data('object'));
}
}
$(document).click(function() {
Module.div();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Now the output is valid :
<div data-object='{"name":"one","type":"two"}' ></div>
You can also set the attribute programmatically with jQuery :
var Module = {
div: function() {
var object = {
name: 'one',
type: 'two'
};
var div = $("<div>")
.attr("data-object", JSON.stringify(object))
.appendTo('body');
console.log(div.data('object'));
}
}
$(document).click(function() {
Module.div();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Replace var html = '<div data-object="' + JSON.stringify(object) + '"></div>';
With var html = '<div data-object=' + JSON.stringify(object) + '></div>';
No need to add the additional double quotes
var Module = {
div: function() {
var object = {
name: 'one',
type: 'two'
};
var html = '<div data-object=' + JSON.stringify(object) + '></div>';
var div = $(html).appendTo('body');
// This just returns "{" instead of my object
console.log(div.data('object'));
}
}
$(document).click(function() {
Module.div();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
</body>

How to use HTML data attributes to return object data?

I'm currently using HTML data attributes to display basic information when an element is clicked using $(this). For example, I have the following HTML snippet:
$('.element').on('click', function(e) {
e.stopPropagation();
$('#info').slideDown();
var title = $(this).data('title');
var desc = $(this).data('desc');
var icon = $(this).data('icon');
var info = $('#info');
info.html('<div class="sub-info"><h1>' + title + '</h1><h1 class="icon">' + icon + '</h1></div><div class="side-info"><p>' + desc + '</p></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element" data-title="title" data-desc="desc" data-icon="H">
It's working as intended but I need more information and keeping it in objects would be a lot cleaner I think. Could anyone point me in the right direction?
In this case you could put all the data in an object, then use the property names of that object in the data attribute to perform the lookup in the click event handler, something like this:
var data = {
foo: {
title: 'title #1',
description: 'description #1',
icon: 'icon #1'
},
bar: {
title: 'title #2',
description: 'description #2',
icon: 'icon #2'
}
};
$('.element').on('click', function(e) {
e.stopPropagation();
var obj = data[$(this).data('key')];
$('#info').html('<div class="sub-info"><h1>' + obj.title + '</h1><h1 class="icon">' + obj.icon + '</h1></div><div class="side-info"><p>' + obj.description + '</p></div>').slideDown();
});
#info {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element" data-key="foo">Lorem</div>
<div class="element" data-key="bar">ipsum</div>
<div id="info"></div>

How to set focus to autocomplete contents on inline edit in free jqgrid

Free jqgrid first column is Jquery UI autocomplete using custom edit type.
Field is made focusable using focusField: true
$.extend(true,$.jgrid.inlineEdit, {
position: "beforeSelected",
focusField: true,
keys: true } );
If inline editing is started, jqgrid puts focus to autocomplete dropdown button.
How to fix this that focus is put to autocomplete input element ?
Autocomplete button is defined with tabindex=-1:
<button type='button' class='btn btn-default btn-form-dropdown' tabindex=-1 aria-label='Open menu'>
<span class='caret'></span></button>
It does not receive focus if tab key is pressed in inline edit.
jqgrid code contains:
getFocusable = function (elem) {
return $(elem).find("input,textarea,select,button,object,*[tabindex]")
.filter(":input:visible:not(:disabled)");
},
So jqgrid puts focus to element even if it contains tabindex=-1
How to fix this ?
Posted also in https://github.com/free-jqgrid/jqGrid/issues/186
Update
Steps to reproduce the issue:
Open page below in Chrome
Select row
Click in inline edit button
Observed:
Button receives focus
Expected:
input element should receive focus
Code to reproduce:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.css" />
<link rel="stylesheet" href="http://rawgit.com/free-jqgrid/jqGrid/master/css/ui.jqgrid.css" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<script src="http://rawgit.com/free-jqgrid/jqGrid/master/js/jquery.jqgrid.src.js"></script>
<script>
$(document).ready(function () {
var mydata = [
{ id: 0, Name: "Indiana", Category: "IN" },
{ id: 1, Name: "California", Category: "CA" },
{ id: 2, Name: "Pennsylvania", Category: "PA" },
{ id: 3, Name: "Texas", Category: "TX" }
];
var lastSel;
var grid = $("#list");
grid.jqGrid({
data: mydata,
datatype: 'local',
colModel: [
{
name: 'Name', editable: true, width: 200,
edittype: 'custom',
editoptions: {
custom_element: combobox_element,
custom_value: function (elem) {
return elem.find("input").val();
}
}
},
{ name: 'Category', index: 'Category', width: 50, editable: true }
],
ignoreCase: true,
gridview: true,
viewrecords: true,
rownumbers: true,
pager: '#pager',
editurl: 'clientArray',
ondblClickRow: function (id, ri, ci) {
grid.jqGrid('editRow', id, true, null, null, 'clientArray', {});
},
onSelectRow: function (id) {
if (id && id !== lastSel) {
if (typeof lastSel !== "undefined") {
grid.jqGrid('restoreRow', lastSel);
}
lastSel = id;
}
}
}).
jqGrid("inlineNav", '#pager');
});
var getColumnByName = function (grid, columnName) {
var cm = grid.jqGrid('getGridParam', 'colModel'), i = 0, l = cm.length;
for (; i < l; ++i) {
if (cm[i].name === columnName) {
return cm[i];
}
}
return null;
};
function combobox_element(value, options) {
var elemStr = '<div><input class="FormElement', newel, width;
if (options.id === options.name) {
elemStr += '" size="' +
options.size + '"' + ' id="' + options.id + '"';
}
else {
elemStr += ' form-control jqgrid-inlineedit-autocomplete" ' +
' style="width:' + width + 'px" ' + ' id="' + options.id + '_x"';
}
elemStr += ' value="' + value + '" lookup="' + options.lookup + '"/>';
elemStr += "<button type='button' class='btn btn-default btn-form-dropdown' tabindex=-1 aria-label='Open menu'>" +
"<span class='caret'></span></button>";
elemStr += '</div>';
newel = $(elemStr)[0];
setTimeout(function () {
input_autocomplete(newel);
}, 50);
return newel;
}
function input_autocomplete(newel) {
var input = $("input", newel);
input.autocomplete({
source: ["Indiana",
"California",
"Pennsylvania"
]
}
);
$("button", newel)
.bind({
click: function () {
input.focus();
}
});
}
</script>
</head>
<body>
<table id="list"></table>
<div id="pager"></div>
</body>
</html>
I'm not sure what you do exactly. Which part of your code place <button type='button' ... tabindex=-1 ...?
Placing of tabindex=-1 means only that the field should not get focus if the user press Tab or Shift-Tab, but it means that the field should do can be focusable via API call. In other wards, the existence of tabindex make it focusable, but the negative value of tabindex informs to exclude the element from sequential focus navigation only. W3 standard formulate it as (see here)
The user agent must set the element's tabindex focus flag, but should
not allow the element to be reached using sequential focus navigation.
One should remove tabindex attribute if one don't want to make the button be focusable.
If you don't create the attribute and it does some control which you use, but you still don't want to set the focus on <button>, then you can just set the focus on another editable column. You can use focusField: "someColumnName" or focusField: indexOfSomeColumn to set the focus on specific column.
UPDATED: I posted the fix which adds the usage of .first() before call of .focus(). After the changes the demo which you posted works good.

Categories

Resources