I have been developing a personal project for a couple of weeks now, and over the past week something changed and the HTML Hidden helper function stopped submitting for some reason and I can't find out why.
Here is the view.
#model GolfTracker.ViewModels.NewRoundViewModel
#{
ViewBag.Title = "NewRound";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>New Round</h2>
#using (Html.BeginForm("Finish", "Rounds"))
{
<div class="form-group">
<p>Select course:</p>
#Html.DropDownListFor(m => m.Round.Course, new SelectList(Model.Courses), "Select course", new { #class = "form-control", #id = "courseDropdown" })
</div>
<table class="table-dark" id="scorecard" style="text-align: center; border: 2px solid #00bc8c; table-layout: fixed">
<thead class="table-secondary">
<th style="vertical-align: middle; padding: 0px; border: 0px">
#
</th>
#for (int i = 1; i < 19; i++)
{
<th style="padding-left: 0px; padding-right: 0px; vertical-align: middle; padding: 0px; border: 0px" width="4.5%">
<div>
#i
</div>
</th>
}
<th style="padding: 0px; border: 0px">
Total
</th>
</thead>
<tr class="table-secondary">
<td style="vertical-align: middle">
Par
</td>
#for (int i = 1; i < 19; i++)
{
<td style="padding-left: 0px; padding-right: 0px; vertical-align: middle">
<div id="hole-#i-par">
</div>
</td>
}
<td>
<div id="par-sum">
</div>
</td>
</tr>
<tr class="table-secondary">
<td style="vertical-align: middle">
Yardage
</td>
#for (int i = 1; i < 19; i++)
{
<td style="padding-left: 0px; padding-right: 0px;">
<div id="hole-#i-yardage">
</div>
</td>
}
<td id="yard-sum"></td>
</tr>
<tr id="scores-array" class="table-secondary">
<td style="vertical-align: middle">
Score
</td>
#for (int i = 1; i < 19; i++)
{
Model.Round.Scores.Add(new GolfTracker.Models.HoleScore()
{
Score = 0
});
<td style="padding-left: 0px; padding-right: 0px;" align="center">
#Html.TextBoxFor(m => m.Round.Scores[i - 1].Score, new { #class = "form-control", #id = "tb-h" + i, #style = "padding-left: 0px; padding-right: 0px; text-align: center; display: block" })
</td>
}
<td id="score-sum"></td>
</tr>
<tr id="putts-array" class="table-secondary">
<td style="vertical-align: middle">
Putts
</td>
#for (int i = 1; i < 19; i++)
{
<td style="padding-left: 0px; padding-right: 0px;" align="center">
#Html.TextBoxFor(m => m.Round.Scores[i - 1].Putts, new { #class = "form-control", #id = "tb-p" + i, #style = "padding-left: 0px; padding-right: 0px; text-align: center; display: block" })
</td>
}
<td id="putts-sum"></td>
</tr>
<tr id="uad-array" class="table-secondary">
<td style="vertical-align: middle">
Up-and-Down
</td>
#for (int i = 1; i < 19; i++)
{
<td style="padding-left: 0px; padding-right: 0px; text-align: center; vertical-align: middle;">
#Html.CheckBoxFor(m => m.Round.Scores[i - 1].UAD, new { #class = "form-check-input", #id = "chb-uad" + i, #style = "margin: 0px; position: relative; width: 20px; height: 20px;" })
</td>
}
<td id="uad-sum"></td>
</tr>
<tr id="ss-array" class="table-secondary">
<td style="vertical-align: middle">
Sand Save
</td>
#for (int i = 1; i < 19; i++)
{
<td style="padding-left: 0px; padding-right: 0px; text-align: center; vertical-align: middle;">
#Html.CheckBoxFor(m => m.Round.Scores[i - 1].SS, new { #class = "form-check-input", #id = "chb-ss" + i, #style = "margin: 0px; position: relative; width: 20px; height: 20px;" })
</td>
}
<td id="ss-sum"></td>
</tr>
</table>
<div class="form-group">
#Html.LabelFor(m => m.Round.Date)
#Html.TextBoxFor(m => m.Round.Date, "{0:d MMM yyyy}", new { #class = "form-control", Type = "date" })
</div>
#Html.Hidden("numHoles", Model.Round.Holes)
#Html.Hidden("score", Model.Round.Score)
#Html.Hidden("putts", Model.Round.Putts)
#Html.Hidden("uad", Model.Round.UAD)
#Html.Hidden("ss", Model.Round.SS)
<div class="form-group">
#Html.LabelFor(m => m.Round.Fairways)
#Html.TextBoxFor(m => m.Round.Fairways, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Round.GIR)
#Html.TextBoxFor(m => m.Round.GIR, new { #class = "form-control" })
</div>
<button type="submit" class="btn btn-primary" id="save">Save</button>
}
Here are the scripts. By the time the user presses the save button, all the data is already calculated and saved to their respective elements. The hidden inputs do indeed have the data, but they don't send it back to the model on submit.
Edit: I am aware there are multiple repeated scripts that could be created through using a loop, but I tried that and it didn't work because each iteration kept using the final index rather than the correct one. I had to resort to declaring them manually.
#section scripts
{
<script>
$(document).ready(function () {
$("#courseDropdown").change(function () {
$.ajax({
type: "GET",
url: "/api/coursesapi/" + $(this).val(),
contentType: "application/json",
success: function (course) {
$("#scorecard").show();
if (course != null) {
var yardSum = 0;
var holeYardage;
var holePar;
for (var i = 1; i < 19; i++) {
holeYardage = document.getElementById("hole-" + i + "-yardage");
holePar = document.getElementById("hole-" + i + "-par");
holeYardage.innerText = course.Holes[i - 1].Length;
holePar.innerText = course.Holes[i - 1].Par;
yardSum += course.Holes[i - 1].Length;
}
document.getElementById("par-sum").innerText = course.Par;
document.getElementById("yard-sum").innerText = yardSum;
}
}
});
});
$("#save").click(function () {
console.log("numHoles: " + $("#numHoles").val());
console.log("score: " + $("#score").val());
console.log("putts: " + $("#putts").val());
console.log("uad: " + $("#uad").val());
console.log("ss: " + $("#ss").val());
});
$("#scores-array").change(function () {
var score;
var sum = 0;
var numHoles = 0;
for (var i = 1; i < 19; i++) {
if (parseInt($("#tb-h" + i).val()) > 0) {
numHoles++;
}
score = $("#tb-h" + i);
sum += parseInt(score.val());
}
document.getElementById("score-sum").innerText = sum;
$("#score").val(sum);
$("#numHoles").val(numHoles);
});
$("#putts-array").change(function () {
var putts;
var sum = 0;
for (var i = 1; i < 19; i++) {
putts = $("#tb-p" + i);
sum += parseInt(putts.val());
}
document.getElementById("putts-sum").innerText = sum;
$("#putts").val(sum);
});
$("#uad-array").change(uadEval);
$("#ss-array").change(function () {
var sum = 0;
for (var i = 1; i < 19; i++) {
if ($("#chb-ss" + i).is(":checked")) {
sum++;
}
}
document.getElementById("ss-sum").innerText = sum;
$("#ss").val(sum);
});
$("#chb-ss1").change(function () {
if ($("#chb-ss1").is(":checked")) {
$("#chb-uad1").prop("checked", true);
$("#chb-uad1").prop("disabled", true);
}
else {
$("#chb-uad1").prop("checked", false);
$("#chb-uad1").prop("disabled", false);
}
uadEval();
});
$("#chb-ss2").change(function () {
if ($("#chb-ss2").is(":checked")) {
$("#chb-uad2").prop("checked", true);
$("#chb-uad2").prop("disabled", true);
}
else {
$("#chb-uad2").prop("checked", false);
$("#chb-uad2").prop("disabled", false);
}
uadEval();
});
$("#chb-ss3").change(function () {
if ($("#chb-ss3").is(":checked")) {
$("#chb-uad3").prop("checked", true);
$("#chb-uad3").prop("disabled", true);
}
else {
$("#chb-uad3").prop("checked", false);
$("#chb-uad3").prop("disabled", false);
}
uadEval();
});
$("#chb-ss4").change(function () {
if ($("#chb-ss4").is(":checked")) {
$("#chb-uad4").prop("checked", true);
$("#chb-uad4").prop("disabled", true);
}
else {
$("#chb-uad4").prop("checked", false);
$("#chb-uad4").prop("disabled", false);
}
uadEval();
});
$("#chb-ss5").change(function () {
if ($("#chb-ss5").is(":checked")) {
$("#chb-uad5").prop("checked", true);
$("#chb-uad5").prop("disabled", true);
}
else {
$("#chb-uad5").prop("checked", false);
$("#chb-uad5").prop("disabled", false);
}
uadEval();
});
$("#chb-ss6").change(function () {
if ($("#chb-ss6").is(":checked")) {
$("#chb-uad6").prop("checked", true);
$("#chb-uad6").prop("disabled", true);
}
else {
$("#chb-uad6").prop("checked", false);
$("#chb-uad6").prop("disabled", false);
}
uadEval();
});
$("#chb-ss7").change(function () {
if ($("#chb-ss7").is(":checked")) {
$("#chb-uad7").prop("checked", true);
$("#chb-uad7").prop("disabled", true);
}
else {
$("#chb-uad7").prop("checked", false);
$("#chb-uad7").prop("disabled", false);
}
uadEval();
});
$("#chb-ss8").change(function () {
if ($("#chb-ss8").is(":checked")) {
$("#chb-uad8").prop("checked", true);
$("#chb-uad8").prop("disabled", true);
}
else {
$("#chb-uad8").prop("checked", false);
$("#chb-uad8").prop("disabled", false);
}
uadEval();
});
$("#chb-ss9").change(function () {
if ($("#chb-ss9").is(":checked")) {
$("#chb-uad9").prop("checked", true);
$("#chb-uad9").prop("disabled", true);
}
else {
$("#chb-uad9").prop("checked", false);
$("#chb-uad9").prop("disabled", false);
}
uadEval();
});
$("#chb-ss10").change(function () {
if ($("#chb-ss10").is(":checked")) {
$("#chb-uad10").prop("checked", true);
$("#chb-uad10").prop("disabled", true);
}
else {
$("#chb-uad10").prop("checked", false);
$("#chb-uad10").prop("disabled", false);
}
uadEval();
});
$("#chb-ss11").change(function () {
if ($("#chb-ss11").is(":checked")) {
$("#chb-uad11").prop("checked", true);
$("#chb-uad11").prop("disabled", true);
}
else {
$("#chb-uad11").prop("checked", false);
$("#chb-uad11").prop("disabled", false);
}
uadEval();
});
$("#chb-ss12").change(function () {
if ($("#chb-ss12").is(":checked")) {
$("#chb-uad12").prop("checked", true);
$("#chb-uad12").prop("disabled", true);
}
else {
$("#chb-uad12").prop("checked", false);
$("#chb-uad12").prop("disabled", false);
}
uadEval();
});
$("#chb-ss13").change(function () {
if ($("#chb-ss13").is(":checked")) {
$("#chb-uad13").prop("checked", true);
$("#chb-uad13").prop("disabled", true);
}
else {
$("#chb-uad13").prop("checked", false);
$("#chb-uad13").prop("disabled", false);
}
uadEval();
});
$("#chb-ss14").change(function () {
if ($("#chb-ss14").is(":checked")) {
$("#chb-uad14").prop("checked", true);
$("#chb-uad14").prop("disabled", true);
}
else {
$("#chb-uad14").prop("checked", false);
$("#chb-uad14").prop("disabled", false);
}
uadEval();
});
$("#chb-ss15").change(function () {
if ($("#chb-ss15").is(":checked")) {
$("#chb-uad15").prop("checked", true);
$("#chb-uad15").prop("disabled", true);
}
else {
$("#chb-uad15").prop("checked", false);
$("#chb-uad15").prop("disabled", false);
}
uadEval();
});
$("#chb-ss16").change(function () {
if ($("#chb-ss16").is(":checked")) {
$("#chb-uad16").prop("checked", true);
$("#chb-uad16").prop("disabled", true);
}
else {
$("#chb-uad16").prop("checked", false);
$("#chb-uad16").prop("disabled", false);
}
uadEval();
});
$("#chb-ss17").change(function () {
if ($("#chb-ss17").is(":checked")) {
$("#chb-uad17").prop("checked", true);
$("#chb-uad17").prop("disabled", true);
}
else {
$("#chb-uad17").prop("checked", false);
$("#chb-uad17").prop("disabled", false);
}
uadEval();
});
$("#chb-ss18").change(function () {
if ($("#chb-ss18").is(":checked")) {
$("#chb-uad18").prop("checked", true);
$("#chb-uad18").prop("disabled", true);
}
else {
$("#chb-uad18").prop("checked", false);
$("#chb-uad18").prop("disabled", false);
}
uadEval();
});
function uadEval() {
var sum = 0;
for (var i = 1; i < 19; i++) {
if ($("#chb-uad" + i).is(":checked")) {
sum++;
}
}
document.getElementById("uad-sum").innerText = sum;
$("#uad").val(sum);
}
});
</script>
}
I used to do the trick with jquery serialize by unhidden all fields before you getting the value and hide it back after everything complete.
I found the issue. For some reason the HTML hidden() helper functions did not have the correct names for the model binding. I think it worked before because the structure of the viewmodel was different, and when I updated the viewmodel the "name" attributes of the hidden fields weren't pointing to valid variables anymore.
Related
I'm pretty new to express and socket.io and I'm trying to achieve a little website:
What is it supposed to do:
You can connect to the website and enter a username
You have to select a column where you want to write (it's stored in var column)
Once on the page with the four column, you can see your username at the top of your column and start doing things there.
The other users see you in the correct column.
What it is not doing:
Actually the three points above are working quite well, my issue is with the last point :
The other users see you in the correct column.
My code is somehow not displaying every user in the correct column, in fact, it's displaying them in the same column as you are
Here is the code
$(document).ready(function () {
var socket = io();
var username = prompt("premier utilisateur : ", "nom");
var column = prompt("colonne ", "1,2,3 ou 4");
var gdhb = "";
socket.emit("new user entered his name");
socket.emit("nomUser", username);
if (column === "1") { column = ".one"; gdhb = ".dir1" }
if (column === "2") { column = ".two"; gdhb = ".dir2" }
if (column === "3") { column = ".three"; gdhb = ".dir3" }
if (column === "4") { column = ".four"; gdhb = ".dir4" }
socket.emit("user chose a column");
socket.emit("columnUser", column);
$(column).append($("<p class='username'>" + username + "</p>"))
$(document.body).click(function (b) {
var verbes = [
"appuie",
"bouscule",
"pousse"
];
var adverbes = [
"puis",
"ensuite",
"pour finir",
"alors"
];
var verbe = verbes[Math.floor(Math.random() * verbes.length)];
var adverbe = adverbes[Math.floor(Math.random() * adverbes.length)];
var verbadv = verbe + " " + adverbe;
console.log(verbadv);
socket.emit("verbadverbe");
socket.emit("verbadv", verbadv);
var div = $("<div />", {
"class": "document"
})
.css({
"left": b.pageX + 'px',
"top": b.pageY + 'px'
})
.append($("<p>" + verbadv + "</p>"))
.appendTo(column);
});
$(document.body).contextmenu(function (rc) {
var div = $("<div />", {
"class": "document"
})
.css({
"left": rc.pageX + 'px',
"top": rc.pageY + 'px'
})
.append($("<p>recule</p>"))
.appendTo(column);
});
var direction = "";
var oldx = 0;
var oldy = 0;
mousemovemethod = function (e) {
if (e.pageX > oldx && e.pageY == oldy) {
direction = "gauche";
}
else if (e.pageX == oldx && e.pageY > oldy) {
direction = "bas";
}
else if (e.pageX == oldx && e.pageY < oldy) {
direction = "haut";
}
else if (e.pageX < oldx && e.pageY == oldy) {
direction = "droite";
}
$(gdhb).append($("<p class='direction' id='direction'>" + direction + "</p>"))
$(".direction").prev().remove();
oldx = e.pageX;
oldy = e.pageY;
}
document.addEventListener('mousemove', mousemovemethod);
socket.on("columnUser", function (column) {
socket.on("nomUser", function (username) {
$(column).append($("<p class='username'>" + username + "</p>"));
socket.on("verbadv", function (verbadv) {
var div = $("<div />", {
"class": "document"
})
.append($("<p>" + verbadv + "</p>"))
.appendTo(column);
});
});
});
});
and the index.js :
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', (socket) => {
console.log('Nouvel utilisateur')
socket.on("nomUser", (username) => {
console.log(username);
io.emit("nomUser", username);
});
socket.on("verbadv", (verbadv) => {
console.log(verbadv);
io.emit("verbadv", verbadv);
});
socket.on("columnUser", (column) => {
console.log(column);
io.emit("columnUser", column);
});
});
server.listen(3000, () => {
console.log('listen on 3000');
})
Also if it's needed to understand better, here is the css
body {
font-family: sans-serif;
font-size: 1.3rem;
margin: 0;
background-color: DarkSlateGray;
}
.wrapper {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 0px;
grid-auto-rows: minmax(100vh, auto);
height: 100vh;
}
.one,
.two,
.three,
.four {
-ms-overflow-style: none; /* Internet Explorer 10+ */
scrollbar-width: none; /* Firefox */
position: relative;
overflow: scroll;
height: 100%;
background-color: tan;
}
.one {
grid-column: 1 / 2;
}
.two {
grid-column: 2 / 3;
}
.three {
grid-column: 3 / 4;
}
.four {
grid-column: 4 / 4;
}
.one::-webkit-scrollbar,
.two::-webkit-scrollbar,
.three::-webkit-scrollbar,
.four::-webkit-scrollbar {
display: none; /* Safari and Chrome */
}
.note {
text-align: center;
width: 100px;
height: 30px;
}
.note p{
filter: drop-shadow(0 0 0.75rem black);
}
.document{
text-align: center;
}
.document p{
padding: 0;
margin: 0;
}
.username{
text-align: center;
padding: 0;
margin: 0;
}
.direction{
position: fixed;
bottom : 0;
width: 25vw;
text-align: center;
}
Thanks a lot for the precious help.
i've solved your problem with sockets. See at my solution.
client.js
function columnIndexIsValid(index, columnsQuantity) {
return index >= 0 && index <= columnsQuantity;
}
function fullNameIsValid(fullName) {
return typeof fullName === 'string' && fullName.length > 2;
}
function reloadPage() {
window.location.reload();
}
function rand(min, max) {
return Math.floor(min + Math.random() * (max - 1 - min));
}
function getRandomColour(colours = []) {
const colour = colours[rand(0, colours.length)];
return `#${colour}`;
}
function getUserHtml(user) {
return `<div class="column__users-list__item" data-item-id="${user.id}">${user.fullName}</div>`;
}
function getDrawnUsersNodes() {
return $('.column__item');
}
function canIRenderUsers(usersQuantity) {
const $renderedUsersQuantity = getDrawnUsersNodes().length;
return $renderedUsersQuantity < usersQuantity;
}
function renderUserHtmlToNode($node, html) {
$node.html($node.html() + html);
}
function getColumnUsersList(columnNode) {
const $column = $(columnNode);
return $column.find('.column__users-list');
}
function removeDrawnUserById(userId) {
$(`[data-item-id=${userId}]`).remove();
}
class DrawnUsers {
constructor() {
this.users = new Map();
}
getUserById(id) {
return this.users.get(id);
}
add(id, state) {
this.users.set(id, state);
}
removeById(id) {
this.users.delete(id);
}
exists(id) {
return this.users.has(id);
}
}
class Storage {
static setItem(key, value) {
localStorage.setItem(key, value);
}
static getItem(key) {
return localStorage.getItem(key) || null;
}
}
function generateUserId() {
return `user-${rand(rand(0, 10000), rand(20000, 50000))}`;
}
class UserState {
constructor() {
this.state = {};
}
get() {
return {
data: this.state,
};
}
set fullName(fullName) {
this.state.fullName = fullName;
}
get fullName() {
return this.state.fullName;
}
set id(id) {
this.state.id = id;
}
get id() {
return this.state.id;
}
set columnIndex(columnIndex) {
this.state.columnIndex = columnIndex - 1;
}
get columnIndex() {
return this.state.columnIndex;
}
}
$(document).ready(function () {
const drawnUsers = new DrawnUsers();
const colours = ['F2994A', 'F2C94C', '6FCF97', '2F80ED', '56CCF2', 'DFA2F5'];
const $columns = $('.column');
const $container = $('.container');
const userState = new UserState();
$columns.each(function () {
const $self = $(this);
$self.css({ 'background-color': getRandomColour(colours) });
});
userState.fullName = prompt('Type your fullName');
userState.columnIndex = +prompt('Type your column number');
if (
!fullNameIsValid(userState.fullName) ||
!columnIndexIsValid(userState.columnIndex, $columns.length)
) {
return reloadPage();
}
$container.addClass('active');
const socket = io('ws://localhost:3000');
socket.on('connect', () => {
const generatedUserId = generateUserId();
userState.id = Storage.getItem('userId') || generatedUserId;
Storage.setItem('userId', userState.id);
socket.emit('connected', userState.get());
socket.emit('addUser', userState.get());
socket.on('updateCurrentUsers', ({ data }) => {
const { users } = data;
if (!users || !canIRenderUsers(users.length)) {
return;
}
users.forEach((user) => {
const $column = $columns[user.columnIndex];
if ($column) {
if (!drawnUsers.exists(user.id)) {
drawnUsers.add(user.id);
renderUserHtmlToNode(
getColumnUsersList($column),
getUserHtml(user)
);
}
}
});
});
socket.on('newUser', ({ data }) => {
console.log('[debug] newUser: ', data);
const $column = $columns[data.columnIndex];
if (!$column) {
return;
}
if (drawnUsers.exists(data.id)) {
drawnUsers.removeById(data.id);
removeDrawnUserById(data.id);
} else {
drawnUsers.add(data.id);
renderUserHtmlToNode(getColumnUsersList($column), getUserHtml(data));
}
});
socket.on('disconnect', () => {
socket.open();
});
});
});
server.js
const path = require('path');
const http = require('http');
const express = require('express');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', (socket) => {
console.log('[debug] Client was connected successfully to server');
socket.on('connected', (user) => {
console.log('connected user data', user.data);
socket.data = user.data;
const users = Array.from(io.sockets.sockets.values()).map(
({ data }) => data
);
console.log('users', users);
socket.emit('updateCurrentUsers', {
data: {
users,
},
});
});
socket.on('addUser', ({ data }) => {
socket.data.columnIndex = data.columnIndex;
socket.broadcast.emit('newUser', {
data,
});
const users = Array.from(io.sockets.sockets.values()).map(
({ data }) => data
);
socket.broadcast.emit('updateCurrentUsers', {
data: {
users,
},
});
});
});
server.listen(3000, () => {
console.log('listen on 3000');
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="./index.css">
<title>Users Columns</title>
</head>
<body>
<div class="container">
<div class="column">
<span class="column__index">#1</span>
<div class="column__users-list"></div>
</div>
<div class="column">
<span class="column__index">#2</span>
<div class="column__users-list"></div>
</div>
<div class="column">
<span class="column__index">#3</span>
<div class="column__users-list"></div>
</div>
<div class="column">
<span class="column__index">#4</span>
<div class="column__users-list"></div>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.1/socket.io.js"
integrity="sha512-vGcPDqyonHb0c11UofnOKdSAt5zYRpKI4ow+v6hat4i96b7nHSn8PQyk0sT5L9RECyksp+SztCPP6bqeeGaRKg=="
crossorigin="anonymous"></script>
<script src="./client.js"></script>
</body>
</html>
index.css
html, body {
box-sizing: border-box;
}
body {
margin: 0;
padding: 0;
}
.container {
display: none;
}
.container.active {
display: flex;
flex-direction: row;
height: 100vh;
}
.container .column {
width: calc(100% / 4);
text-align: center;
padding: 20px 0;
}
.container .column .column__users-list {
display: flex;
flex-direction: column;
}
.container .column .column__index {
color: #FFF;
font-size: 36px;
letter-spacing: 8px;
}
hey) Let's look on that case more attentive, you have created a variable what contains a column index. right? This variable does store inside var variable. That is global variable for your script. I think you need to store each user column info inside each socket. If you don't know, each socket contains some info inside itself like id and other what can be used in your project if you'd like. But for this case you need to do so:
Ask new user what column he would like to choose.
Write to his socket data/info his column index.
When you do broadcast (It's when you send an object of data to each socket in room all each socket at all) just take this column index and draw this user in correct position. But make sure what your var column has a correct value. I can advice you to use const/let in javascript :)
i'm trying to implement drag and drop with dynamicllay created containers and droppable items
on click of a button droppable section will get created dynamically
there will be unordered list of elements with static text like Email filed, Phone number field , multile options,etcc..
ondrag of any of these list item i want to create new element dynamically based on the static filed type(email,phone,miltiple checkbox)
need to insert new element on drop i have created a partially working code but somehow this is not working properly i suspect something i need to do with dataTransfer object.
This is partially working i was able to create element dynamically and append it to the dom but but while dragging around not working as i expected. any help would be appreciated.
let draggables = document.querySelectorAll('.draggable');
let containers = document.querySelectorAll('.container');
let mainContainer = document.getElementById('main-container');
let afterElement;
let elementToInsert;
let count = 0;
let addsec = document.getElementById('addsection');
addsec.addEventListener('click',function(e){
let container = document.createElement('div');
container.classList.add('container');
let section = document.createElement('h1');
section.innerHTML = `Section ${count++}`;
container.appendChild(section);
mainContainer.appendChild(container)
init();
})
draggables.forEach(draggable => {
draggable.addEventListener('dragstart', (e) => {
e.stopPropagation();
console.log("drag start",e,draggable);
if(draggable && draggable.getAttribute('name')){
let element = draggable.getAttribute('name');
switch(element){
case 'text-field':
elementToInsert = document.createElement('input');
elementToInsert.classList.add('draggable');
elementToInsert.setAttribute('draggable',true);
elementToInsert.setAttribute('placeholder','Text');
elementToInsert.setAttribute('disabled',true);
break;
case 'email-field':
elementToInsert = document.createElement('input');
elementToInsert.classList.add('draggable');
elementToInsert.setAttribute('draggable',true);
elementToInsert.setAttribute('placeholder','Email');
elementToInsert.setAttribute('disabled',true);
break;
case 'phone-field':
elementToInsert = document.createElement('input');
elementToInsert.classList.add('draggable');
elementToInsert.setAttribute('draggable',true);
elementToInsert.setAttribute('placeholder','Phone');
elementToInsert.setAttribute('disabled',true);
break;
default:
elementToInsert = draggable;
break;
}
}else{
elementToInsert = draggable;
}
elementToInsert.addEventListener('dragstart',function(ev){
ev.dataTransfer.setData('elementid',ev.target.id);
})
elementToInsert.setAttribute('id',`field-${Date.now()}`);
draggable.classList.add('dragging')
})
draggable.addEventListener('dragend', () => {
draggable.classList.remove('dragging')
})
})
function init(){
draggables = document.querySelectorAll('.draggable');
containers = document.querySelectorAll('.container');
console.log("draggables",draggables,containers);
containers.forEach(container => {
container.addEventListener('dragover', e => {
e.preventDefault()
let data = e.dataTransfer.getData("elementid");
console.log("eee",data);
afterElement = getDragAfterElement(container, e.clientY);
if (afterElement == null) {
container.appendChild(elementToInsert)
} else {
container.insertBefore(elementToInsert, afterElement)
}
})
container.addEventListener('drop', e => {
e.preventDefault()
let data = e.dataTransfer.getData("elementid");
// console.log("ff",data);
draggables = document.querySelectorAll('.draggable');
// init();
})
container.addEventListener('dragleave', e => {
e.preventDefault();
})
container.addEventListener('dragenter', e => {
e.preventDefault();
})
})
}
function getDragAfterElement(container, y) {
const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')]
return draggableElements.reduce((closest, child) => {
const box = child.getBoundingClientRect()
const offset = y - box.top - box.height / 2
if (offset < 0 && offset > closest.offset) {
return { offset: offset, element: child }
} else {
return closest
}
}, { offset: Number.NEGATIVE_INFINITY }).element
}
body {
margin: 0;
}
h1{
color:#fff;
}
.container {
background-color: #333;
padding: 1rem;
margin: 1rem;
width: 200px;
}
.draggable {
padding: 1rem;
background-color: white;
border: 1px solid black;
cursor: move;
}
.draggable.dragging {
opacity: .5;
}
#main-container{
display: flex;
}
input{
display: block;
width:83%;
height: 0px;
}
.main{
display: flex;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<link rel="stylesheet" type="text/css" href="index.css" >
</head>
<body>
<div class="main">
<div>
<div class="draggable" name="text-field" draggable="true">Text Field</div>
<div class="draggable" name="email-field" draggable="true">Email Field</div>
<div class="draggable" name="phone-field" draggable="true">Phone Field</div>
</div>
<div id="main-container">
<!-- <div class="container">
<h1>Section 1</h1>
<p class="draggable" draggable="true">1</p>
<p class="draggable" draggable="true">2</p>
</div>
<div class="container">
<h1>Section 2</h1>
<p class="draggable" draggable="true">3</p>
<p class="draggable" draggable="true">4</p>
</div> -->
</div>
</div>
<button id="addsection">Add section</button>
<script src="index.js"></script>
</body>
</html>
Finally i figured not sure this is the right way but it is working for my requirement
function CustomDragAndDrop(){
this.draggables = undefined;
this.containers = undefined;
this.placeholder = undefined;
this.elementToInsert = undefined;
this.afterElement = undefined;
this.sectionCount = 0;
this.mainContainer = undefined;
this.existingElement = undefined;
this.addSection = function(){
let container = document.createElement('div');
container.classList.add('container');
let section = document.createElement('h1');
section.innerHTML = `Section ${this.sectionCount++}`;
container.appendChild(section);
console.log("this main container",this.mainContainer);
this.mainContainer.appendChild(container);
this.addEventListenersForContainer(container);
this.updateContainers();
}
this.updateContainers = function(){
this.containers = document.querySelectorAll('.container');
}
this.updateDraggables = function(){
this.draggables = document.querySelectorAll('.draggable');
}
this.addEventListeners = function(name){
console.log("adding event listeners",this.containers,this.draggables);
if(name === 'containers' && this.containers){
this.containers.forEach(container => {
container.addEventListener('dragover',e => this.onDragHover(e,container,false));
container.addEventListener('drop',e => this.onDragDrop(e),false);
container.addEventListener('dragleave',e => this.onDragLeave(e),false);
container.addEventListener('dragenter',e => this.onDragEnter(e),false);
});
}else if('draggables' && this.draggables){
this.draggables.forEach(draggable => {
draggable.addEventListener('dragstart',e => this.onDragStart(e,draggable),false);
draggable.addEventListener('dragend', e => this.onDragEnd(e,draggable),false);
});
}else if(this.draggables && this.containers){
this.containers.forEach(container => {
container.addEventListener('dragover',e => this.onDragHover(e,container),false);
container.addEventListener('drop', e => this.onDragDrop(e),false);
container.addEventListener('dragleave',e => this.onDragLeave(e),false);
container.addEventListener('dragenter',e => this.onDragEnter(e),false);
});
this.draggables.forEach(draggable => {
draggable.addEventListener('dragstart',e => this.onDragStart(e),false);
draggable.addEventListener('dragend', e => this.onDragEnd(e),false);
});
}
console.log("draggables",this.draggables);
console.log("this.containers",this.containers);
}
this.removeEventListeners = function(name){
if(name === 'container' && this.containers){
this.containers.forEach(container => {
container.removeEventListener('dragover',e => this.onDragHover(e,container),false);
container.removeEventListener('drop', e => this.onDragDrop(e),false);
container.removeEventListener('dragleave',e => this.onDragLeave(e),false);
container.removeEventListener('dragenter',e => this.onDragEnter(e),false);
});
}else if(name === 'draggables' && this.draggables){
this.draggables.forEach(draggable => {
draggable.removeEventListener('dragstart',e => this.onDragStart(e,draggable),false);
draggable.removeEventListener('dragend', e => this.onDragEnd(e,draggable),false);
});
}else if(this.draggables && this.containers){
this.containers.forEach(container => {
container.removeEventListener('dragover',e => this.onDragHover(e,container),false);
container.removeEventListener('drop',e => this.onDragDrop(e),false);
container.removeEventListener('dragleave',e => this.onDragLeave(e),false);
container.removeEventListener('dragenter',e => this.onDragEnter(e),false);
});
this.draggables.forEach(draggable => {
draggable.removeEventListener('dragstart',e => this.onDragStart(e),false);
draggable.removeEventListener('dragend',e => this.onDragEnd(e),false);
});
}
}
this.createPlaceHolder = function(){
let placeholder = document.createElement('div');
placeholder.style.height = '50px';
placeholder.style.borderRadius = '5px';
placeholder.style.backgroundColor = '#eee';
placeholder.style.margin = '10px 0';
this.placeholder = placeholder;
}
this.getDragAfterElement = function(container, y){
const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')]
return draggableElements.reduce((closest, child) => {
const box = child.getBoundingClientRect()
const offset = y - box.top - box.height / 2
if (offset < 0 && offset > closest.offset) {
return { offset: offset, element: child }
} else {
return closest
}
}, { offset: Number.NEGATIVE_INFINITY }).element
}
this.onDragStart = function(e,draggable){
e.stopPropagation();
let elementToInsert;
console.log("drag start",draggable);
// e.dataTransfer.setData('elementid',e.target.id);
if(draggable && draggable.getAttribute('name')){
let element = draggable.getAttribute('name');
switch(element){
case 'text-field':
elementToInsert = document.createElement('input');
elementToInsert.classList.add('draggable');
elementToInsert.setAttribute('draggable',true);
elementToInsert.setAttribute('placeholder','Text');
elementToInsert.setAttribute('disabled',true);
elementToInsert.setAttribute('id',`field-${Date.now()}`);
this.elementToInsert = elementToInsert;
this.existingElement = false;
break;
case 'email-field':
elementToInsert = document.createElement('input');
elementToInsert.classList.add('draggable');
elementToInsert.setAttribute('draggable',true);
elementToInsert.setAttribute('placeholder','Email');
elementToInsert.setAttribute('disabled',true);
elementToInsert.setAttribute('id',`field-${Date.now()}`);
this.elementToInsert = elementToInsert;
this.existingElement = false;
break;
case 'phone-field':
elementToInsert = document.createElement('input');
elementToInsert.classList.add('draggable');
elementToInsert.setAttribute('draggable',true);
elementToInsert.setAttribute('placeholder','Phone');
elementToInsert.setAttribute('disabled',true);
elementToInsert.setAttribute('id',`field-${Date.now()}`);
this.elementToInsert = elementToInsert;
this.existingElement = false;
break;
default:
this.elementToInsert = draggable;
this.existingElement = true;
break;
}
}else{
this.existingElement = true;
this.elementToInsert = draggable;
}
this.placeholder.setAttribute("id",`placeholder-${Date.now()}`);
draggable.classList.add('dragging');
}
this.onDragEnd = function(e,draggable){
draggable.classList.remove('dragging');
console.log("drag end",this.elementToInsert);
if(!this.existingElement){
this.addEventListenerForDraggableItem(this.elementToInsert);
this.updateDraggables('draggables');
}else{
console.log("existing ele",this.elementToInsert);
this.elementToInsert.classList.remove('dragging');
}
}
this.addEventListenerForDraggableItem = function(element){
console.log("ele",element);
element.addEventListener('dragstart',e => this.onDragStart(e,element));
element.addEventListener('dragend',e => this.onDragEnd(e,element));
}
this.addEventListenersForContainer = function(container){
container.addEventListener('dragover',e => this.onDragHover(e,container,false));
container.addEventListener('drop',e => this.onDragDrop(e),false);
container.addEventListener('dragleave',e => this.onDragLeave(e),false);
container.addEventListener('dragenter',e => this.onDragEnter(e),false);
}
this.onDragHover = function(e,container){
e.preventDefault();
this.afterElement = this.getDragAfterElement(container, e.clientY);
if (this.afterElement == null) {
container.appendChild(this.placeholder)
} else {
container.insertBefore(this.placeholder, this.afterElement)
}
}
this.onDragEnter = function(e){
e.preventDefault();
}
this.onDragLeave = function(e){
e.preventDefault();
console.log("on drag leave");
}
this.onDragDrop = function(e){
e.preventDefault()
// let data = e.dataTransfer.getData("elementid");
this.placeholder.replaceWith(this.elementToInsert);
}
this.init = function(){
try{
this.mainContainer = document.getElementById('main-container');
this.updateContainers();
this.updateDraggables();
this.addEventListeners();
this.createPlaceHolder();
}catch(e){
console.log(e);
}
}
}
let customDragnDrop = new CustomDragAndDrop();
customDragnDrop.init();
body {
margin: 0;
}
h1{
color:#fff;
}
.container {
background-color: #333;
padding: 1rem;
margin: 1rem;
width: 200px;
}
.draggable {
padding: 1rem;
background-color: white;
border: 1px solid black;
cursor: move;
}
.draggable.dragging {
opacity: .5;
}
#main-container{
display: flex;
}
input{
display: block;
width:83%;
height: 0px;
}
.main{
display: flex;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<link rel="stylesheet" type="text/css" href="index.css" >
</head>
<body>
<div class="main">
<div>
<div class="draggable" id="text" name="text-field" draggable="true">Text Field</div>
<div class="draggable" id="email" name="email-field" draggable="true">Email Field</div>
<div class="draggable" id="phone" name="phone-field" draggable="true">Phone Field</div>
</div>
<div id="main-container">
<!-- <div class="container">
<h1>Section 1</h1>
<p class="draggable" draggable="true">1</p>
<p class="draggable" draggable="true">2</p>
</div>
<div class="container">
<h1>Section 2</h1>
<p class="draggable" draggable="true">3</p>
<p class="draggable" draggable="true">4</p>
</div> -->
</div>
</div>
<button onclick="customDragnDrop.addSection()">Add section</button>
<script src="index.js"></script>
</body>
</html>
I am looking to have a + change to a - when my table row expands. I have provided my code below and also through JS Fiddle here: https://jsfiddle.net/k37f0cbp/2/
$(document).ready(function() {
$('tr.parent')
.css("cursor", "pointer")
.attr("title", "click")
.click(function() {
$(this).siblings('.child-' + this.id).toggle();
});
$('tr[#class^=child-]').children('td').hide();
});
$if(('tr[#class^=child-]').is(":visible")).click(function() {
$('.plus', this).html('-');
});
th,
td {
border-bottom: 1px solid black;
}
th,
td {
padding: 15px;
}
tr:hover {
background-color: #f5f5f5;
}
[class*='child-row'] {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table style="width:100%">
<tbody>
<tr class="parent" id="row1" title="click">
<td><span class="plus">+</span></td>
<td>Paper Idea One</td>
</tr>
<tr class="child-row1">
<td>testing</td>
</tr>
</tbody>
</table>
$(document).ready(function ()
{
//add a flag
var expanded = false;
$('tr.parent')
.css("cursor", "pointer")
.attr("title", "click")
.click(function ()
{
$(this).siblings('.child-' + this.id).toggle();
//check flag, update value of a button and update a flag
if(expanded)
{
$(".plus").text("+");
expanded = false;
}
else
{
$(".plus").text("-");
expanded = true;
}
});
$('tr[#class^=child-]').children('td').hide();
});
$if (('tr[#class^=child-]').is(":visible")).click(function()
{
$('.plus', this).html('-');
});
After many more hours exploring this, I combined what the contributor above added with some other things I experimented with and came up with a more elegant and accurate answer that accounts for multiple rows. The only trick here is adding an id to the plus element that is equivalent to the parents id.
$(document).ready(function ()
$('tr.parent')
.css("cursor", "pointer")
.attr("title", "click")
.click(function ()
{
$(this).siblings('.child-' + this.id).toggle();
var s = this.id;
if ($(this).next().is(":visible")) {
$('#' + s + '.plus').html('-');
}
if ($(this).next().is(":hidden")) {
$('#' + s + '.plus').html('+');
}
})
)};
I've a table inside a div inside the main.
all of this have width = 100% but when i make the window smaller just the div ant the main gets smaller but the table dosent resize. all other elements below the table change position and size and starts lay over it. the table has 25 records and if the window is full-size everything matches perfect.
The div im talkin about has the id home
The html:
<DOCTYPE! html>
<html>
<head>
<meta charset="UTF-8">
<title>Admin Panel | Please Login</title>
<link href='../css/admin.css' type='text/css' rel='stylesheet'>
<meta http-equiv="refresh" content="60">
</head>
<body>
<main>
<div id='container'>
<img src="../img/ipw_quer_rgb.jpg" alt="IPW Logo" id="logo" width="15%">
<header>
<ul id='menu'>
<div id="links">
<li>Home</li>
<li>Schüler verwalten</li>
<li>History</li>
</div>
</ul>
</header>
<div id="home">
<h2 id="date"></h2>
<table id="table">
</table>
</div>
<div id="dropdown" class="dropdown">
<select id="select">
<option value="Nothing">Nichts ausgewählt</option>
<option value="Extern">Extern</option>
<option value="Termin">Termin</option>
<option value="Schule">Schule</option>
</select>
</div>
<div id="legend" class="legend">
<svg width="10" height="10">
<rect x="0" y="0" width="10" height="10" style="fill:#D3D3D3;" />
</svg>
<a>Extern</a>
<br>
<svg width="10" height="10">
<rect x="0" y="0" width="10" height="10" style="fill:#FFAEB9;" />
</svg>
<a>Termin</a>
<br>
<svg width="10" height="10">
<rect x="0" y="0" width="10" height="10" style="fill:#FFFF00;" />
</svg>
<a>Schule</a>
<br>
<svg width="10" height="10">
<rect x="0" y="0" width="10" height="10" style="fill:#00FF00;" />
</svg>
<a>Visiert</a>
<br>
<button id="edit">Editieren</button>
</div>
</div>
</main>
the css:
*{
margin: 0;
padding: 0;
font-family: monospace;
box-sizing: border-box;
}
main{
height: 100%;
width: 100%;
}
label{
font: 13px Helvetica, Arial, sans-serif;
}
html, body{
background-color: #006975;
overflow-y:auto;
height: 100%;
width: 100%;
padding: 0;
margin: 0;
}
h3{
margin-right:50%;
}
table{
width:100%;
height:calc(100% -50px);
}
ul {
width:100%;
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #006975;
}
li {
width:25%;
float: left;
}
h1{
text-align:center;
}
li a {
display: block;
color: white;
font-size: 120%;
text-align: center;
padding: 14px 16px;
border-left: 2px solid #fff;
border-right: 2px solid #fff;
text-decoration: none;
}
/* Change the link color to #111 (black) on hover */
li a:hover {
color: #006975;
background-color: #fff;
}
button:hover{
color:#fff;
background-color:#84afb8;
}
#container{
position:absolute;
margin: 4% 4% 4% 4%;
padding: 2%;
width: 90%;
height: 90%;
background-color: #fff;
}
#home{
height:60%;
}
#dropdown{
width:100%;
height:2%;
visibility:hidden;
}
.cell {
height: 4%;
width:10%;
text-align: center;
background-color: #D3D3D3;
}
.cell.on {
height: 4%;
width: 10%;
background-color: #00FF00;
}
.cell.les {
height: 4%;
width: 10%;
background-color: #FFFF00;
}
.cell.term {
height: 4%;
width: 10%;
background-color: #FFAEB9;
}
.cell.ext{
height: 4%;
width: 10%;
background-color: #D3D3D3;
}
.cell.spacer {
height: 4%;
width: 10%;
background-color:white;
}
.name {
border: 1px solid black;
}
if you also need the javascript please ask
EDIT:
javascript:
getDataUser('logGLAUSB');
var names = ["Zebra","Benj", "Nico", "Timon","Miro", "Leo"];
var longpresstimer = null;
getData();
window.addEventListener('click', function(){
});
window.addEventListener('load', function () {
var clickcount = 0;
var singleClickTimer;
document.getElementById('table').addEventListener('click', function (event) {
clickcount++;
if(clickcount==1){
if(event.target.tagName != "INPUT" && event.target.classList != 'cell spacer'){
singleClickTimer = setTimeout(function() {
clickcount = 0;
var cell = event.target;
var selected = getSelected();
if(selected == 3){
cell.classList.remove("ext");
cell.classList.remove("term");
cell.classList.remove("les");
cell.classList.add("on");
}else{
cell.classList.remove("ext");
cell.classList.remove("term");
cell.classList.remove("les");
cell.classList.remove("on");
switch(selected){
case 0: cell.classList.add("ext"); break;
case 1: cell.classList.add("les"); break;
case 2: cell.classList.add("term"); break;
}
}
var x = "get";
x += getString(event.target.parentNode.cells[0].childNodes[0].innerHTML);
getData(x);
}, 300);
}
}else if (clickcount == 2){
if(event.target.classList != "name"){
clearTimeout(singleClickTimer);
clickcount = 0;
toInput(event.target);
}
}
});
});
document.getElementById("edit").addEventListener('click', function(){
var legend = document.getElementById("legend");
var dropdown = document.getElementById('dropdown');
var select = document.getElementById('select');
legend.style.visibility = 'hidden';
dropdown.style.visibility = 'visible';
var button = document.createElement('button');
button.innerHTML= "Fertig";
dropdown.appendChild(button);
button.onclick = function(){
legend.style.visibility = 'visible';
dropdown.style.visibility = 'hidden';
dropdown.removeChild(button);
select.value = "Nothing";
}
});
function reset(){
var rows = Array.from(document.getElementsByClassName('row'));
var table = document.getElementById('table');
rows.forEach(function (row){
var cells = Array.from(document.getElementsByClassName('cell'));
for(var i = 0;i< cells.length;i++){
var cell = cells[i]
cell.classList.remove('on');
cell.classList.remove('les');
cell.classList.remove('term');
cell.classList.remove('ext');
}
});
var x = "rep";
x += getResetString();
getData(x);
}
function clearSelection() {
if(document.selection && document.selection.empty) {
document.selection.empty();
} else if(window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
}
}
function getData(str) {
var requestURL = "http://adopraesenz.ipwin.ch/data/students.php?q=" +str;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200){
loadJson(request);
}
};
request.open("GET", requestURL, true);
request.send();
}
function getDataHistory(str) {
var requestURL = "http://adopraesenz.ipwin.ch/data/history.php?q=" +str;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200){
if(request.responseText != ""){
loadDate(request);
}
}
};
request.open("GET", requestURL, true);
request.send();
}
function getDataUser(str){
var requestURL = "http://adopraesenz.ipwin.ch/data/login.php?q=" +str;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200){
if(request.responseText != ""){
loadDate(request);
} }
};
request.open("GET", requestURL, true);
request.send();
}
function getSelected(cell) {
var value = document.getElementById("select").value;
switch(value){
case "Extern": return 0; break;
case "Schule": return 1; break;
case "Termin": return 2; break;
default: return 3;
}
}
function loadDate(request){
var newDate = new Date();
newDate.setDate(newDate.getDate() -1);
newDate.setHours(0,0,0,0);
var days = request.responseText.split(".");
var oldDate = new Date(days[1]+"."+days[0]+"."+days[2]);
if(newDate > oldDate){
var date = new Date();
date.setDate(date.getDate() - 1);
var dd = date.getDate();
var mm = date.getMonth() + 1;
var yyyy = date.getFullYear();
if(dd < 10) {
dd = '0' +dd;
}
if(mm < 10) {
mm = '0' +mm;
}
var yesterday = dd+"."+mm+"."+yyyy;
getDataHistory('add' + yesterday);
reset();
}
newDate = new Date().toLocaleDateString('de-CH', {
weekday: 'long',
day: '2-digit',
month: '2-digit',
year: 'numeric'
});
document.getElementById('date').innerHTML = newDate;
}
getDataHistory('new');
function loadJson(request){
createTable(request.responseText);
}
function createHeader(array){
var header = document.createElement("thead");
var hRow = document.createElement('tr');
hRow.classList.add('header');
for(var i = 0; i < array.length; i++){
var div = document.createElement('div');
var th = document.createElement('th');
div.innerHTML = array[i];
th.appendChild(div);
hRow.appendChild(th);
}
header.appendChild(hRow);
return header;
}
function createTable(json){
var obj = JSON.parse(json);
var oldBody = document.getElementsByTagName('tbody')[0];
console.log(oldBody);
var oldHeader = document.getElementsByTagName('thead')[0];
var body = document.createElement('tbody');
var header = createHeader(["Name","09:00 – 09:45","10:15 – 11:00","11:00 – 11:45"," ","14:00 – 14:45","15:00 - 15:45","16:00 – 16:45"]);
for (var j = 0; j < obj.length; j++) {
var row = addRow(obj[j],body);
row.classList.add('row');
}
console.log(body);
replaceTable(body, oldBody, header ,oldHeader);
if(obj.length > 25){
var view = document.getElementById('home');
view.setAttribute("style", "overflow-y:scroll");
}
}
function toInput(cell){
var input = document.createElement('input');
setTimeout(function() { input.focus(); }, 200);
cell.appendChild(input);
window.addEventListener('keypress', function(e){
if(e.keyCode == '13'){
var text = input.value;
if(input.parentNode != null){
input.parentNode.removeChild(input);
}
cell.innerHTML = text;
getData("get"+getString(cell.parentNode.cells[0].childNodes[0].innerHTML));
}
}, false);
}
function replaceTable(body, oldBody, header, oldHeader){
if(typeof oldHeader == 'undefined'){
table.appendChild(header);
}else if(oldHeader.parentNode == table){
table.replaceChild(header, oldHeader);
}else{
table.appendChild(header);
}
if(typeof oldBody == 'undefined'){
table.appendChild(body);
}else if(oldBody.parentNode == table){
table.removeChild(oldBody);
table.appendChild(body);
//table.replaceChild(body, oldBody);
}else{
table.appendChild(body);
}
}
function addRow(val,body) {
var rest = val.split(";");
var tr = document.createElement('tr');
for( var i = 0; i < 8; i++){
if(i==0){
var name = rest[0];
addCell(tr, null,name);
}else{
var value = rest[i];
addCell(tr, value, name);
}
}
body.appendChild(tr);
return tr;
}
function addCell(tr, val, name) {
var name;
var cell = document.createElement('td');
var value = "get";
if(val == null){
var input = document.createElement('label');
cell.classList.add("name")
input.innerHTML = name;
input.readOnly = true;
cell.appendChild(input);
}else{
cell = document.createElement('td');
cell.classList.add('cell');
var content = val.split(":");
switch(content[0]){
case '0': cell.classList.add('ext'); break;
case '1': cell.classList.add('les'); break;
case '2': cell.classList.add('term'); break;
case '3': cell.classList.add('on'); break;
case '4': cell.classList.add('spacer'); break;
}
if(val.length > 1){
cell.innerHTML = content[1];
}
}
tr.appendChild(cell);
}
window.onclick = function(event) {
if (!event.target.matches('.dropA')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
function getString(name){
var x = "";
var names = document.getElementsByClassName('name');
var values = document.getElementsByClassName('cell');
for(var i = 0;i<names.length;i++){
if(names[i].childNodes[0].innerHTML == name){
x+= names[i].childNodes[0].innerHTML + ";";
for(var j = (7 * i); j < (7 * i) + 7 ; j++){
switch(""+values[j].classList){
case 'cell': x += "0"; break;
case 'cell ext': x += "0"; break;
case 'cell les': x += "1"; break;
case 'cell term': x += "2"; break;
case 'cell on': x += "3"; break;
case 'cell spacer': x += "4"; break;
}
if(values[j].innerHTML != "" && values[j].innerHTML != null){
x+= ":" + values[j].innerHTML
}
x += ";";
}
}
}
return x;
}
function getResetString(){
var names = document.getElementsByClassName('name');
var x = "";
for(var i = 0; i < names.length; i++){
x += names[i].value +";";
for (var j = 0; j < 7 ; j++){
if(j == 3){
x += "4";
}else{
x += "0";
}
x += ";";
}
if(i < names.length-1){
x+="|";
}
}
return x;
}
it seems a tiny problem. on your css, you have to add an space on the calc statement:
height:calc(100% - 50px);
I was able to make it work in here
https://codesandbox.io/s/vibrant-http-ty85k
You can add display: table; to #container
and add:
#legend {
display: table-row;
}
This should work, but I think you should refactor (simplify) the whole page and styles.
I have a codes on Jsfiddle but not showing on realtime project i have consider external resources. Jfiddle has a tab menu and each tab is showing different chart on it like bar chart or pie chart or line chart.
I put both the css and js files on same page and also on the different page than also its not showing the js function on other tab.
Please let me know the solution i am trying from very long but its not working.
Jsfiddle
<div id="TabbedPanels1" class="TabbedPanels">
<ul class="TabbedPanelsTabGroup">
<li class="TabbedPanelsTab" tabindex="0">Tab 1</li>
<li class="TabbedPanelsTab" tabindex="0">Tab 2</li>
</ul>
<div class="TabbedPanelsContentGroup">
<div class="TabbedPanelsContent">
<div id="jQueryVisualizeChart1"></div>
<br />
<table id="table1">
<caption>2010 Employee Sales by Department</caption>
<thead>
<tr>
<td></td>
<th scope="col">food</th>
<th scope="col">auto</th>
<th scope="col">household</th>
<th scope="col">furniture</th>
<th scope="col">kitchen</th>
<th scope="col">bath</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Mary</th>
<td>190</td>
<td>160</td>
<td>40</td>
<td>120</td>
<td>30</td>
<td>70</td>
</tr>
<tr>
<th scope="row">Tom</th>
<td>3</td>
<td>40</td>
<td>30</td>
<td>45</td>
<td>35</td>
<td>49</td>
</tr>
</tbody>
</table>
</div>
<div class="TabbedPanelsContent">
<div id="jQueryVisualizeChart2"></div>
<br />
<table id="table2">
<caption>2010 Employee Sales by Department</caption>
<thead>
<tr>
<td></td>
<th scope="col">food</th>
<th scope="col">auto</th>
<th scope="col">household</th>
<th scope="col">furniture</th>
<th scope="col">kitchen</th>
<th scope="col">bath</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Mary</th>
<td>190</td>
<td>160</td>
<td>40</td>
<td>120</td>
<td>30</td>
<td>70</td>
</tr>
<tr>
<th scope="row">Tom</th>
<td>3</td>
<td>40</td>
<td>30</td>
<td>45</td>
<td>35</td>
<td>49</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
(function () { // BeginSpryComponent
if (typeof Spry == "undefined") window.Spry = {};
if (!Spry.Widget) Spry.Widget = {};
Spry.Widget.TabbedPanels = function (element, opts) {
this.element = this.getElement(element);
this.defaultTab = 0; // Show the first panel by default.
this.tabSelectedClass = "TabbedPanelsTabSelected";
this.tabHoverClass = "TabbedPanelsTabHover";
this.tabFocusedClass = "TabbedPanelsTabFocused";
this.panelVisibleClass = "TabbedPanelsContentVisible";
this.focusElement = null;
this.hasFocus = false;
this.currentTabIndex = 0;
this.enableKeyboardNavigation = true;
this.nextPanelKeyCode = Spry.Widget.TabbedPanels.KEY_RIGHT;
this.previousPanelKeyCode = Spry.Widget.TabbedPanels.KEY_LEFT;
Spry.Widget.TabbedPanels.setOptions(this, opts);
if (typeof (this.defaultTab) == "number") {
if (this.defaultTab < 0) this.defaultTab = 0;
else {
var count = this.getTabbedPanelCount();
if (this.defaultTab >= count) this.defaultTab = (count > 1) ? (count - 1) : 0;
}
this.defaultTab = this.getTabs()[this.defaultTab];
}
if (this.defaultTab) this.defaultTab = this.getElement(this.defaultTab);
this.attachBehaviors();
};
Spry.Widget.TabbedPanels.prototype.getElement = function (ele) {
if (ele && typeof ele == "string") return document.getElementById(ele);
return ele;
};
Spry.Widget.TabbedPanels.prototype.getElementChildren = function (element) {
var children = [];
var child = element.firstChild;
while (child) {
if (child.nodeType == 1 /* Node.ELEMENT_NODE */ ) children.push(child);
child = child.nextSibling;
}
return children;
};
Spry.Widget.TabbedPanels.prototype.addClassName = function (ele, className) {
if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) != -1)) return;
ele.className += (ele.className ? " " : "") + className;
};
Spry.Widget.TabbedPanels.prototype.removeClassName = function (ele, className) {
if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) == -1)) return;
ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), "");
};
Spry.Widget.TabbedPanels.setOptions = function (obj, optionsObj, ignoreUndefinedProps) {
if (!optionsObj) return;
for (var optionName in optionsObj) {
if (ignoreUndefinedProps && optionsObj[optionName] == undefined) continue;
obj[optionName] = optionsObj[optionName];
}
};
Spry.Widget.TabbedPanels.prototype.getTabGroup = function () {
if (this.element) {
var children = this.getElementChildren(this.element);
if (children.length) return children[0];
}
return null;
};
Spry.Widget.TabbedPanels.prototype.getTabs = function () {
var tabs = [];
var tg = this.getTabGroup();
if (tg) tabs = this.getElementChildren(tg);
return tabs;
};
Spry.Widget.TabbedPanels.prototype.getContentPanelGroup = function () {
if (this.element) {
var children = this.getElementChildren(this.element);
if (children.length > 1) return children[1];
}
return null;
};
Spry.Widget.TabbedPanels.prototype.getContentPanels = function () {
var panels = [];
var pg = this.getContentPanelGroup();
if (pg) panels = this.getElementChildren(pg);
return panels;
};
Spry.Widget.TabbedPanels.prototype.getIndex = function (ele, arr) {
ele = this.getElement(ele);
if (ele && arr && arr.length) {
for (var i = 0; i < arr.length; i++) {
if (ele == arr[i]) return i;
}
}
return -1;
};
Spry.Widget.TabbedPanels.prototype.getTabIndex = function (ele) {
var i = this.getIndex(ele, this.getTabs());
if (i < 0) i = this.getIndex(ele, this.getContentPanels());
return i;
};
Spry.Widget.TabbedPanels.prototype.getCurrentTabIndex = function () {
return this.currentTabIndex;
};
Spry.Widget.TabbedPanels.prototype.getTabbedPanelCount = function (ele) {
return Math.min(this.getTabs().length, this.getContentPanels().length);
};
Spry.Widget.TabbedPanels.addEventListener = function (element, eventType, handler, capture) {
try {
if (element.addEventListener) element.addEventListener(eventType, handler, capture);
else if (element.attachEvent) element.attachEvent("on" + eventType, handler);
} catch (e) {}
};
Spry.Widget.TabbedPanels.prototype.cancelEvent = function (e) {
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
if (e.stopPropagation) e.stopPropagation();
else e.cancelBubble = true;
return false;
};
Spry.Widget.TabbedPanels.prototype.onTabClick = function (e, tab) {
this.showPanel(tab);
return this.cancelEvent(e);
};
Spry.Widget.TabbedPanels.prototype.onTabMouseOver = function (e, tab) {
this.addClassName(tab, this.tabHoverClass);
return false;
};
Spry.Widget.TabbedPanels.prototype.onTabMouseOut = function (e, tab) {
this.removeClassName(tab, this.tabHoverClass);
return false;
};
Spry.Widget.TabbedPanels.prototype.onTabFocus = function (e, tab) {
this.hasFocus = true;
this.addClassName(tab, this.tabFocusedClass);
return false;
};
Spry.Widget.TabbedPanels.prototype.onTabBlur = function (e, tab) {
this.hasFocus = false;
this.removeClassName(tab, this.tabFocusedClass);
return false;
};
Spry.Widget.TabbedPanels.KEY_UP = 38;
Spry.Widget.TabbedPanels.KEY_DOWN = 40;
Spry.Widget.TabbedPanels.KEY_LEFT = 37;
Spry.Widget.TabbedPanels.KEY_RIGHT = 39;
Spry.Widget.TabbedPanels.prototype.onTabKeyDown = function (e, tab) {
var key = e.keyCode;
if (!this.hasFocus || (key != this.previousPanelKeyCode && key != this.nextPanelKeyCode)) return true;
var tabs = this.getTabs();
for (var i = 0; i < tabs.length; i++)
if (tabs[i] == tab) {
var el = false;
if (key == this.previousPanelKeyCode && i > 0) el = tabs[i - 1];
else if (key == this.nextPanelKeyCode && i < tabs.length - 1) el = tabs[i + 1];
if (el) {
this.showPanel(el);
el.focus();
break;
}
}
return this.cancelEvent(e);
};
Spry.Widget.TabbedPanels.prototype.preorderTraversal = function (root, func) {
var stopTraversal = false;
if (root) {
stopTraversal = func(root);
if (root.hasChildNodes()) {
var child = root.firstChild;
while (!stopTraversal && child) {
stopTraversal = this.preorderTraversal(child, func);
try {
child = child.nextSibling;
} catch (e) {
child = null;
}
}
}
}
return stopTraversal;
};
Spry.Widget.TabbedPanels.prototype.addPanelEventListeners = function (tab, panel) {
var self = this;
Spry.Widget.TabbedPanels.addEventListener(tab, "click", function (e) {
return self.onTabClick(e, tab);
}, false);
Spry.Widget.TabbedPanels.addEventListener(tab, "mouseover", function (e) {
return self.onTabMouseOver(e, tab);
}, false);
Spry.Widget.TabbedPanels.addEventListener(tab, "mouseout", function (e) {
return self.onTabMouseOut(e, tab);
}, false);
if (this.enableKeyboardNavigation) {
var tabIndexEle = null;
var tabAnchorEle = null;
this.preorderTraversal(tab, function (node) {
if (node.nodeType == 1 /* NODE.ELEMENT_NODE */ ) {
var tabIndexAttr = tab.attributes.getNamedItem("tabindex");
if (tabIndexAttr) {
tabIndexEle = node;
return true;
}
if (!tabAnchorEle && node.nodeName.toLowerCase() == "a") tabAnchorEle = node;
}
return false;
});
if (tabIndexEle) this.focusElement = tabIndexEle;
else if (tabAnchorEle) this.focusElement = tabAnchorEle;
if (this.focusElement) {
Spry.Widget.TabbedPanels.addEventListener(this.focusElement, "focus", function (e) {
return self.onTabFocus(e, tab);
}, false);
Spry.Widget.TabbedPanels.addEventListener(this.focusElement, "blur", function (e) {
return self.onTabBlur(e, tab);
}, false);
Spry.Widget.TabbedPanels.addEventListener(this.focusElement, "keydown", function (e) {
return self.onTabKeyDown(e, tab);
}, false);
}
}
};
Spry.Widget.TabbedPanels.prototype.showPanel = function (elementOrIndex) {
var tpIndex = -1;
if (typeof elementOrIndex == "number") tpIndex = elementOrIndex;
else // Must be the element for the tab or content panel.
tpIndex = this.getTabIndex(elementOrIndex);
if (!tpIndex < 0 || tpIndex >= this.getTabbedPanelCount()) return;
var tabs = this.getTabs();
var panels = this.getContentPanels();
var numTabbedPanels = Math.max(tabs.length, panels.length);
for (var i = 0; i < numTabbedPanels; i++) {
if (i != tpIndex) {
if (tabs[i]) this.removeClassName(tabs[i], this.tabSelectedClass);
if (panels[i]) {
this.removeClassName(panels[i], this.panelVisibleClass);
panels[i].style.display = "none";
}
}
}
this.addClassName(tabs[tpIndex], this.tabSelectedClass);
this.addClassName(panels[tpIndex], this.panelVisibleClass);
panels[tpIndex].style.display = "block";
this.currentTabIndex = tpIndex;
};
Spry.Widget.TabbedPanels.prototype.attachBehaviors = function (element) {
var tabs = this.getTabs();
var panels = this.getContentPanels();
var panelCount = this.getTabbedPanelCount();
for (var i = 0; i < panelCount; i++)
this.addPanelEventListeners(tabs[i], panels[i]);
this.showPanel(this.defaultTab);
};
})();
$(function () {
$('#table1').visualize({
type: 'bar',
height: '260px',
width: '420px',
appendTitle: true,
lineWeight: 4,
colors: ['#be1e2d', '#666699', '#92d5ea', '#ee8310', '#8d10ee', '#5a3b16', '#26a4ed', '#f45a90', '#e9e744']
}).appendTo('#jQueryVisualizeChart').trigger('visualizeRefresh1');
});
$(function () {
$('#table2').visualize({
type: 'line',
height: '300px',
width: '420px',
appendTitle: true,
lineWeight: 4,
colors: ['#be1e2d', '#666699', '#92d5ea', '#ee8310', '#8d10ee', '#5a3b16', '#26a4ed', '#f45a90', '#e9e744']
}).appendTo('#jQueryVisualizeChart').trigger('visualizeRefresh2');
});
var TabbedPanels1 = new Spry.Widget.TabbedPanels("TabbedPanels1");
.dwpeAd {
color: #333;
background-color: #F4F3Ea;
position:fixed;
right: 20px;
top: 20px;
padding: 5px;
}
.visualize {
margin: 20px 0 0 30px;
}
.TabbedPanels {
overflow: hidden;
margin: 0px;
padding: 0px;
clear: none;
width: 100%;
}
.TabbedPanelsTabGroup {
margin: 0px;
padding: 0px;
}
.TabbedPanelsTab {
position: relative;
top: 1px;
float: left;
padding: 4px 10px;
margin: 0px 1px 0px 0px;
font: bold 0.7em sans-serif;
background-color: #DDD;
list-style: none;
border-left: solid 1px #CCC;
border-bottom: solid 1px #999;
border-top: solid 1px #999;
border-right: solid 1px #999;
-moz-user-select: none;
-khtml-user-select: none;
cursor: pointer;
}
.TabbedPanelsTabHover {
background-color: #CCC;
}
.TabbedPanelsTabSelected {
background-color: #EEE;
border-bottom: 1px solid #EEE;
}
.TabbedPanelsTab a {
color: black;
text-decoration: none;
}
.TabbedPanelsContentGroup {
clear: both;
border-left: solid 1px #CCC;
border-bottom: solid 1px #CCC;
border-top: solid 1px #999;
border-right: solid 1px #999;
background-color: #EEE;
}
.TabbedPanelsContent {
overflow: hidden;
padding: 4px;
}
.TabbedPanelsContentVisible {
}
.VTabbedPanels {
overflow: hidden;
zoom: 1;
}
.VTabbedPanels .TabbedPanelsTabGroup {
float: left;
width: 10em;
height: 20em;
background-color: #EEE;
position: relative;
border-top: solid 1px #999;
border-right: solid 1px #999;
border-left: solid 1px #CCC;
border-bottom: solid 1px #CCC;
}
.VTabbedPanels .TabbedPanelsTab {
float: none;
margin: 0px;
border-top: none;
border-left: none;
border-right: none;
}
.VTabbedPanels .TabbedPanelsTabSelected {
background-color: #EEE;
border-bottom: solid 1px #999;
}
.VTabbedPanels .TabbedPanelsContentGroup {
clear: none;
float: left;
padding: 0px;
width: 30em;
height: 20em;
}
/* Styles for Printing */
#media print {
.TabbedPanels {
overflow: visible !important;
}
.TabbedPanelsContentGroup {
display: block !important;
overflow: visible !important;
height: auto !important;
}
.TabbedPanelsContent {
overflow: visible !important;
display: block !important;
clear:both !important;
}
.TabbedPanelsTab {
overflow: visible !important;
display: block !important;
clear:both !important;
}
}
I think you did not copy the 'external resources' on left menu.