Data input auto formatting using Javascript - javascript

I'm working on a date input auto formatting solution. The code I use adds a space between before and after a slash (example : 02 / 02 / 2006.
I tried to avoid this behavior. So instead, the date format is 02/02/2006.
I'm also using an Event Delegation to make the date formatting active on all the inputs.
Actually, I tried a solution to deactivate space adding. But the modification doesn't allow the control of the input to delete dates.
function checkValue(str, max) {
if (str.charAt(0) !== '0' || str == '00') {
var num = parseInt(str);
if (isNaN(num) || num <= 0 || num > max) num = 1;
str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString();
};
return str;
};
function dateInput(date) { // date is input object argument
var input = date.value;
if (/\D\/$/.test(input))
input = input.substr(0, input.length - 3);
var values = input.split('/').map(function(v) {
return v.replace(/\D/g, '')
});
if (values[0]) {
values[0] = checkValue(values[0], 12);
}
if (values[1]) {
values[1] = checkValue(values[1], 31);
}
var output = values.map(function(v, i) {
return v.length == 2 && i < 2 ? v + ' / ' : v;
});
date.value = output.join('').substr(0, 14);
}
function dateBlur(date) { // date is input object argument
var input = date.value;
var values = input.split('/').map(function(v, i) {
return v.replace(/\D/g, '')
});
var output = '';
if (values.length == 3) {
var year = values[2].length !== 4 ? parseInt(values[2]) + 2000 : parseInt(values[2]);
var month = parseInt(values[0]) - 1;
var day = parseInt(values[1]);
var d = new Date(year, month, day);
if (!isNaN(d)) {
document.getElementById('result').innerText = d.toString();
var dates = [d.getMonth() + 1, d.getDate(), d.getFullYear()];
output = dates.map(function(v) {
v = v.toString();
return v.length == 1 ? '0' + v : v;
}).join(' / ');
}
}
date.value = output;
}
// delegate event handling from the form element
var form = document.getElementById("form");
form.addEventListener("blur", function(e) {
if(e.target.dataset.type == "date") {
dateBlur(e.target);
}
},false);
form.addEventListener("input", function(e) {
if(e.target.dataset.type == "date") {
dateInput(e.target);
}
}, false);
html {
box-sizing: border-box;
font-family: 'PT Sans', sans-serif;
-webkit-font-smoothing: antialiased;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
background-color: #f3f3f3;
}
form {
width: 100%;
max-width: 400px;
margin: 60px auto;
}
form input {
font-size: 30px;
padding: 0 20px;
border: 2px solid #ccc;
width: 100%;
color: #666;
line-height: 3;
border-radius: 7px;
font-family: 'PT Sans', sans-serif;
font-weight: bold;
}
form input:focus {
outline: 0;
}
form input.error {
border-color: #ff0000;
}
form label.error {
background-color: #ff0000;
color: #fff;
padding: 6px;
font-size: 11px;
}
label {
color: #999;
display: block;
margin-bottom: 10px;
text-transform: uppercase;
font-size: 18px;
font-weight: bold;
letter-spacing: 0.05em
}
form small {
color: #888;
font-size: 1em;
margin-top: 10px;
display: block;
align-self: ;
}
<form id="form" method="post" action="">
<label for="amount">Date</label>
<input type="text" id="date1" data-type="date" />
<small>Enter date as Month / Day / Year</small>
</br>
<label for="amount">Date 2</label>
<input type="text" id="date2" data-type="date" />
<small>Enter date as Month / Day / Year</small>
</br>
<label for="amount">Date 3</label>
<input type="text" id="date3" data-type="date" />
<small>Enter date as Month / Day / Year</small>
</form>

First you need to remove ' / ' and replace with '/',
And you need to change substr(0, 14) to substr(0, 10)
You can also specify maxlength="10" to your html input box
Try following snippet.
function checkValue(str, max) {
if (str.charAt(0) !== '0' || str == '00') {
var num = parseInt(str);
if (isNaN(num) || num <= 0 || num > max) num = 1;
str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString();
};
return str;
};
function dateInput(date) { // date is input object argument
var input = date.value;
if (/\D\/$/.test(input))
input = input.substr(0, input.length - 3);
var values = input.split('/').map(function(v) {
return v.replace(/\D/g, '')
});
if (values[0]) {
values[0] = checkValue(values[0], 12);
}
if (values[1]) {
values[1] = checkValue(values[1], 31);
}
var output = values.map(function(v, i) {
return v.length == 2 && i < 2 ? v + '/' : v;
});
date.value = output.join('').substr(0, 10);
}
function dateBlur(date) { // date is input object argument
var input = date.value;
var values = input.split('/').map(function(v, i) {
return v.replace(/\D/g, '')
});
var output = '';
if (values.length == 3) {
var year = values[2].length !== 4 ? parseInt(values[2]) + 2000 : parseInt(values[2]);
var month = parseInt(values[0]) - 1;
var day = parseInt(values[1]);
var d = new Date(year, month, day);
if (!isNaN(d)) {
document.getElementById('result').innerText = d.toString();
var dates = [d.getMonth() + 1, d.getDate(), d.getFullYear()];
output = dates.map(function(v) {
v = v.toString();
return v.length == 1 ? '0' + v : v;
}).join('/');
}
}
date.value = output;
}
// delegate event handling from the form element
var form = document.getElementById("form");
form.addEventListener("blur", function(e) {
if(e.target.dataset.type == "date") {
dateBlur(e.target);
}
},false);
form.addEventListener("input", function(e) {
if(e.target.dataset.type == "date") {
dateInput(e.target);
}
}, false);
html {
box-sizing: border-box;
font-family: 'PT Sans', sans-serif;
-webkit-font-smoothing: antialiased;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
background-color: #f3f3f3;
}
form {
width: 100%;
max-width: 400px;
margin: 60px auto;
}
form input {
font-size: 30px;
padding: 0 20px;
border: 2px solid #ccc;
width: 100%;
color: #666;
line-height: 3;
border-radius: 7px;
font-family: 'PT Sans', sans-serif;
font-weight: bold;
}
form input:focus {
outline: 0;
}
form input.error {
border-color: #ff0000;
}
form label.error {
background-color: #ff0000;
color: #fff;
padding: 6px;
font-size: 11px;
}
label {
color: #999;
display: block;
margin-bottom: 10px;
text-transform: uppercase;
font-size: 18px;
font-weight: bold;
letter-spacing: 0.05em
}
form small {
color: #888;
font-size: 1em;
margin-top: 10px;
display: block;
align-self: ;
}
<form id="form" method="post" action="">
<label for="amount">Date</label>
<input type="text" id="date1" data-type="date" maxlength="10"/>
<small>Enter date as Month / Day / Year</small>
</br>
<label for="amount">Date 2</label>
<input type="text" id="date2" data-type="date" maxlength="10"/>
<small>Enter date as Month / Day / Year</small>
</br>
<label for="amount">Date 3</label>
<input type="text" id="date3" data-type="date" maxlength="10" />
<small>Enter date as Month / Day / Year</small>
</form>

Related

trying to make a wordle game, but the letters are going up to down, instead of right to left, i don't know how to tackle it

I am making a 4x4 wordle game, and I used js to make the squares and input letters. When I input letters they go top to bottom instead of left to right and I'm not really sure how to fix it. I don't know how to modify the key events to go from the first column to the second, this is the code that deals with it, but I don't know why it isn't working, i feel like the code that is affecting it is this, but im not sure
if (col < gameWidth) {
let currsquare = document.getElementById(row.toString() + '-' + col.toString());
currsquare.innerText = e.code[3];
col++;
}
var gameHeight = 4; //number of guesses
var gameWidth = 4; //length of the word
var row = 0; //current guess (attempt #)
var col = 0; //current letter for that attempt
var gameOver = false;
var word = "RAAA";
window.onload = function() {
initialize();
};
function initialize() {
const darkModeToggle = document.getElementById("dark-mode-toggle");
darkModeToggle.addEventListener("click", () => {
document.body.classList.toggle("dark");
});
const instructionsToggle = document.getElementById("info");
const instructionsContainer = document.getElementById("instructions-container");
// Hide the instructions by default
instructionsContainer.style.display = "none";
// Show or hide the instructions when the button is clicked
instructionsToggle.addEventListener("click", () => {
if (instructionsContainer.style.display === "none") {
instructionsContainer.style.display = "block";
} else {
instructionsContainer.style.display = "none";
}
});
// Create the game board
for (let i = 0; i < gameHeight; i++) {
let row = document.createElement("div");
row.classList.add("row");
for (let j = 0; j < gameWidth; j++) {
let square = document.createElement("span");
square.id = i.toString() + "-" + j.toString();
square.classList.add("square");
square.innerText = "";
row.appendChild(square);
}
document.getElementById("board").appendChild(row);
}
// Listen for Key Press
document.addEventListener("keyup", (e) => {
if (gameOver) return;
if ("KeyA" <= e.code && e.code <= "KeyZ") {
if (col < gameWidth) {
let currsquare = document.getElementById(row.toString() + '-' + col.toString());
currsquare.innerText = e.code[3];
col++;
}
} else if (e.code == "Backspace") {
if (col > 0) {
col--;
let currsquare = document.getElementById(row.toString() + '-' + col.toString());
currsquare.innerText = "";
}
} else if (e.code == "Enter") {
update();
row += 1; // start new row
col = 0; // reset current index to 0 for new row
}
if (!gameOver && row == gameHeight) {
gameOver = true;
document.getElementById("answer").innerText = word;
}
});
}
function update() {
let correct = 0;
for (let column = 0; column < gameWidth; column++) {
let currsquare = document.getElementById(row.toString() + '-' + column.toString());
let letter = currsquare.innerText;
// Is it in the correct position?
if (word[row*gameWidth + (column % gameWidth)] == letter) {
currsquare.classList.add("correct");
correct += 1;
} // Is it in the word?
else if (word.includes(letter)) {
currsquare.classList.add("present");
} // Not in the word
else {
currsquare.classList.add("absent");
}
}
if (correct == gameWidth) {
gameOver = true;
document.getElementById("congrats").style.display = "block";
}
if (!gameOver && row == gameHeight - 1) {
gameOver = true;
document.getElementById("answer").innerText = word;
}
}
this is the updated html
<html>
<head>
<title>Wordle</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale = 1.0">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.15.3/css/all.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" />
<link rel="stylesheet" href="wordle.css">
</head>
<body>
<h1 id="title">Wordle</h1>
<i id = "info" class="fas fa-info-circle"></i>
<i id="dark-mode-toggle" class="fas fa-circle"></i>
<hr>
<br>
<div id="board">
</div>
<br>
<div id="instructions-container">
<p>The goal is to guess the word </p>
</div>
<img id="congrats" src="https://res.cloudinary.com/mkf/image/upload/v1675467141/ENSF-381/labs/congrats_fkscna.gif" alt="Congratulations">
<script src="wordle.js"></script>
</html>
This is the updated css
body {
font-family: Arial, Helvetica, sans-serif;
text-align: center;
--correct:#6baa64;
--background-color:white;
--text-color:black;
color: var(--text-color);
background-color: var(--background-color);
}
body.dark{
font-family: Arial, Helvetica, sans-serif;
text-align: center;
--correct:#6baa64;
--background-color:black;
background-color: var(--background-color);
--text-color:white;
color:white;
}
hr {
width: 500px;
}
#title {
font-size: 36px;
font-weight: bold;
letter-spacing: 2px;
}
#board {
width: 350px;
height: 420px;
margin: 0 auto;
margin-top: 3px;
display: flex;
flex-wrap: wrap;
}
.square {
border: 2px solid lightgray;
width: 60px;
height: 60px;
margin: 2.5px;
color: black;
font-size: 36px;
font-weight: bold;
display: flex;
justify-content: center;
align-items: center;
}
.correct {
background-color: var(--correct);
color: white;
border-color: white;
}
.present {
background-color: #C9B458;
color: white;
border-color: white;
}
.absent {
background-color: #787C7E;
color: white;
border-color:white;
}
#congrats {
display: none;
}
#dark-mode-toggle {
position: fixed;
top: 10px;
right: 250px;
}
#question{
position: fixed;
top: 10px;
right: 200px;
}
#info{
position: fixed;
top: 10px;
right: 300px;
}
You dont need display: flex; in board but you need to add display: flex; to row
#board {
width: 350px;
height: 420px;
margin: 0 auto;
margin-top: 3px;
}
.row {
display: flex;
}

JS Calendar breaks on certain months

everyone!
I am fairly new to the coding field, I was trying to create a JS calendar that starts with Monday but it breaks on certain months, like that:
Screenshot
I think it happens only when monday is the first day of the month and only for upcoming months.
var Cal = function(divId) {
//Store div id
this.divId = divId;
// Days of week, starting on Sunday
this.DaysOfWeek = [
'Mon',
'Tue',
'Wed',
'Thu',
'Fri',
'Sat',
'Sun'
];
// Months, stating on January
this.Months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];
// Set the current month, year
var d = new Date();
this.currMonth = d.getMonth();
this.currYear = d.getFullYear();
this.currDay = d.getDate();
};
// Goes to next month
Cal.prototype.nextMonth = function() {
if ( this.currMonth == 11 ) {
this.currMonth = 0;
this.currYear = this.currYear + 1;
}
else {
this.currMonth = this.currMonth + 1;
}
this.showcurr();
};
// Goes to previous month
Cal.prototype.previousMonth = function() {
if ( this.currMonth == 0 ) {
this.currMonth = 11;
this.currYear = this.currYear - 1;
}
else {
this.currMonth = this.currMonth - 1;
}
this.showcurr();
};
// Show current month
Cal.prototype.showcurr = function() {
this.showMonth(this.currYear, this.currMonth);
};
// Show month (year, month)
Cal.prototype.showMonth = function(y, m) {
var d = new Date()
// First day of the week in the selected month
, firstDayOfMonth = new Date(y, m, 1).getDay()
// Last day of the selected month
, lastDateOfMonth = new Date(y, m+1, 0).getDate()
// Last day of the previous month
, lastDayOfLastMonth = m == 0 ? new Date(y-1, 11, 0).getDate() : new Date(y, m, 0).getDate();
var html = '<table>';
// Write selected month and year
html += '<thead><tr>';
html += '<td colspan="7" class="header">' + this.Months[m] + ' ' + y + '</td>';
html += '</tr></thead>';
// Write the header of the days of the week
html += '<tr class="days">';
for(var i=0; i < this.DaysOfWeek.length;i++) {
html += '<td>' + this.DaysOfWeek[i] + '</td>';
}
html += '</tr>';
// Write the days
var i=1;
do {
var dow = new Date(y, m, i).getDay();
// If Sunday, start new row
if ( dow == 1 ) {
html += '<tr>';
}
// If not Sunday but first day of the month
// it will write the last days from the previous month
else if ( i == 1 ) {
html += '<tr>';
var k = lastDayOfLastMonth - firstDayOfMonth;
for(var j=1; j < firstDayOfMonth; j++) {
html += '<td class="not-current">' + k + '</td>';
k++;
}
}
// Write the current day in the loop
var chk = new Date();
var chkY = chk.getFullYear();
var chkM = chk.getMonth();
if (chkY == this.currYear && chkM == this.currMonth && i == this.currDay) {
html += '<td class="today">' + i + '</td>';
} else {
html += '<td class="normal">' + i + '</td>';
}
// If Saturday, closes the row
if ( dow == 0 ) {
html += '</tr>';
}
// If not Saturday, but last day of the selected month
// it will write the next few days from the next month
else if ( i == lastDateOfMonth ) {
var k=7;
for(dow; dow < 7; dow++) {
html += '<td class="not-current">' + k + '</td>';
k++;
}
}
i++;
}while(i <= lastDateOfMonth);
// Closes table
html += '</table>';
// Write HTML to the div
document.getElementById(this.divId).innerHTML = html;
};
// On Load of the window
window.onload = function() {
// Start calendar
var c = new Cal("divCal");
c.showcurr();
// Bind next and previous button clicks
getId('btnNext').onclick = function() {
c.nextMonth();
};
getId('btnPrev').onclick = function() {
c.previousMonth();
};
}
// Get element by id
function getId(id) {
return document.getElementById(id);
}
html,
body {
height: 100%;
}
body {
font-size: 100%;
line-height: 1.5;
font-family: monospace;
background: #fff;
color: #fff;
}
*,
*:before,
*:after {
box-sizing: border-box;
}
.group:after {
content: "";
display: table;
clear: both;
}
img {
max-width: 100%;
height: auto;
vertical-align: baseline;
}
a {
text-decoration: none;
}
.calendar-wrapper {
width: 360px;
margin: 3em auto;
padding: 2em;
border: 1px solid black;
border-radius: 5px;
background: #fff;
box-shadow: 2px 2px 1px 0px #000000;
}
table {
clear: both;
width: 100%;
border: 2px solid black;
border-radius: 3px;
border-collapse: collapse;
color: #444;
}
td {
height: 48px;
text-align: center;
vertical-align: middle;
border-right: 2px solid black;
border-top: 2px solid black;
width: 14.28571429%;
}
td.header {
background: #f3fff3;
font-weight: bold;
}
td.not-current {
color: #c0c0c0;
}
td.today {
font-weight: 700;
color: #28283b;
font-size: 1.5em;
}
thead td {
border: none;
color: #28283b;
text-transform: uppercase;
font-size: 1.5em;
}
#btnPrev {
float: left;
margin-bottom: 20px;
}
#btnPrev:before {
content: '\f104';
font-family: FontAwesome;
padding-right: 4px;
}
#btnNext {
float: right;
margin-bottom: 20px;
}
#btnNext:after {
content: '\f105';
font-family: FontAwesome;
padding-left: 4px;
}
#btnPrev,
#btnNext {
background: transparent;
border: none;
outline: none;
font-size: 1em;
color: #c0c0c0;
cursor: pointer;
font-family: monospace;
text-transform: uppercase;
transition: all 0.3s ease;
}
#btnPrev:hover,
#btnNext:hover {
color: #28283b;
font-weight: bold;
}
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Calendar Widget for Notion by Neon</title>
<meta name='viewport' content='width=device-width, initial-scale=1'><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel='stylesheet' href='//fonts.googleapis.com/css?family=Roboto:400|Roboto+Condensed:400|Fjalla+One:400'>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css'>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<!-- partial:index.partial.html -->
<div class="calendar-wrapper">
<button id="btnPrev" type="button">Prev</button>
<button id="btnNext" type="button">Next</button>
<div id="divCal"></div>
</div>
<!-- partial -->
<script src="./script.js"></script>
</body>
</html>
Would love if anyone could provide any guidance to this issue.

javascript function causing postback on asp.net

This following javascript is causing an unwanted postback on asp.net webform codebehind:
mini_cal.on("click, focusin", ".a-date", function(){
if(!$(this).hasClass('blurred'))
showEvent($(this).data('event'));
});`
It's from a calendar control and the function is called when you click on a date. Adding e.preventDefault() stops the postback but then showEvent() is not called. On a plain html page everything works fine, but I need this on an aspx page cause I need to pull the events from db, server side. I hope someone could come up with a solution, since the author himself does not seem to be able to come up with one.
Ok, here's the aspx page:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="caltest.aspx.vb" Inherits="caltest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="css/mini-event-calendar.css" />
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="js/mini-event-calendar.js?v=7"></script>
<script>
var db_events = [
{
title: "Board members meeting.",
date: 1532381440036,
link: "events.com/ev2"
},
{
title: "Delaware branch opening.",
date: 1532467961534,
link: "events.com/ev1"
},
{
title: "An important event.",
date: 1532554405128,
link: "events.com/ev1"
}
];
$(document).ready(function () {
$("#calendar").MEC({
calendar_link: "example.com/myCalendar",
events: db_events
});
//if you don't have events, use
// $("#calendar2").MEC();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>With events...</h3>
<div id="calendar" runat="server" style="width: 30%;margin-right:auto;margin-left:auto;"></div> <br>
</div>
</form>
</body>
</html>
mini-event-calendar.js
(function( $ ) {
var calenderTpl = '<div id="calTitle"><button class="month-mover prev"><svg fill="#FFFFFF" height="30" viewBox="0 0 24 24" width="30" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/><path d="M0 0h24v24H0z" fill="none"/></svg></button><div id="monthYear"></div><button class="month-mover next"><svg fill="#FFFFFF" height="30" viewBox="0 0 24 24" width="30" xmlns="http://www.w3.org/2000/svg"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/><path d="M0 0h24v24H0z" fill="none"/></svg></button></div><div><div id="calThead"><div>S</div><div>M</div><div>T</div><div>W</div><div>T</div><div>F</div><div>S</div></div><div id="calTbody"></div></div><div id="calTFooter"><h3 id="eventTitle">No events today.</h3>ALL EVENTS</div>';
var short_months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul","Aug", "Sep", "Oct", "Nov", "Dec"];
var today = new Date();
var cur_month = today.getMonth();
var cur_year = today.getFullYear();
$.fn.miniEventCalendar = $.fn.MEC = function(options) {
var settings = $.extend({
calendar_link : "",
events: []
}, options );
var mini_cal = this;
mini_cal.addClass('mini-cal').html(calenderTpl);
var tbody = mini_cal.find("#calTbody");
var cal_title = mini_cal.find("#monthYear");
var cal_footer = mini_cal.find("#calTFooter");
var event_title = mini_cal.find("#eventTitle");
var events_link = mini_cal.find("#calLink");
cal_title.text("Feb 2018");
event_title.text("No events today.");
events_link.text("ALL EVENTS");
events_link.attr("href", settings.calendar_link);
if(!settings.calendar_link.length && !settings.events.length)
cal_footer.css("display", "none");
mini_cal.find(".month-mover").each(function(){
var mover = $(this);
mover.bind("click", function(){
if(mover.hasClass("next"))
viewNextMonth();
else
viewPrevMonth();
});
});
mini_cal.on("click, focusin", ".a-date", function(){
if(!$(this).hasClass('blurred'))
showEvent($(this).data('event'));
});
function populateCalendar(month, year) {
tbody.html("");
cal_title.text(short_months[month] + " " + year);
cur_month = month;
cur_year = year;
var ldate = new Date(year, month);
var dt = new Date(ldate);
if(ldate.getDate() === 1 && dt.getDay() != 1)
tbody.append(last_prev_month_days(dt.getDay()));
while (ldate.getMonth() === month) {
dt = new Date(ldate);
var isToday = areSameDate(ldate, new Date());
var event = null;
var event_index = settings.events.findIndex(function(ev) {
return areSameDate(dt, new Date(ev.date));
});
if(event_index != -1){
event = settings.events[event_index];
if(isToday)
showEvent(event);
}
tbody.append(date_tpl(false, ldate.getDate(), isToday, event));
ldate.setDate(ldate.getDate() + 1);
var buffer_days = 43 - mini_cal.find(".a-date").length;
if(ldate.getMonth() != month)
for (var i = 1; i < buffer_days; i++)
tbody.append(date_tpl(true, i));
}
}
function last_prev_month_days(day){
if(cur_month > 0){
var month_idx = cur_month - 1;
var year_idx = cur_year;
}else{
if(cur_month < 11){
var month_idx = 0;
var year_idx = cur_year + 1;
}else{
var month_idx = 11;
var year_idx = cur_year - 1;
}
}
var prev_month = getMonthDays(month_idx, year_idx);
var last_days = "";
for (var i = day; i > 0; i--)
last_days += date_tpl(true, prev_month[ prev_month.length - i]);
return last_days;
}
function date_tpl(blurred, date, is_today, event){
var tpl = "<div class='a-date blurred'><span>"+date+"</span></div>";
if(!blurred){
var cls = is_today ? "current " : "";
cls += event && event !== null ? "event " : "";
var tpl ="<button class='a-date "+cls+"' data-event='"+JSON.stringify(event)+"'><span>"+date+"</span></button>";
}
return tpl;
}
function showEvent(event){
if(event && event !== null && event !== undefined){
event_title.text(event.title);
events_link.text("VIEW EVENT");
events_link.attr("href", event.link);
}else{
event_title.text("No events on this day.");
events_link.text("ALL EVENTS");
events_link.attr("href", settings.calendar_link);
}
}
function viewNextMonth(){
var next_month = cur_month < 11 ? cur_month + 1 : 0;
var next_year = cur_month < 11 ? cur_year : cur_year + 1;
populateCalendar(next_month, next_year);
}
function viewPrevMonth(){
var prev_month = cur_month > 0 ? cur_month - 1 : 11;
var prev_year = cur_month > 0 ? cur_year : cur_year - 1;
populateCalendar(prev_month, prev_year);
}
function areSameDate(d1, d2) {
return d1.getFullYear() == d2.getFullYear()
&& d1.getMonth() == d2.getMonth()
&& d1.getDate() == d2.getDate();
}
function getMonthDays(month, year) {
var date = new Date(year, month, 1);
var days = [];
while (date.getMonth() === month) {
days.push(date.getDate());
date.setDate(date.getDate() + 1);
}
return days;
}
populateCalendar(cur_month, cur_year);
return mini_cal;
};
}( jQuery ));
mini-event-calendar.css
.mini-cal{
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
font-family: Verdana, sans-serif;
padding-bottom: 1.2em;
background: #22252e;
color: #fff;
}
#calTitle{
display: flex;
justify-content: space-between;
-ms-align-items: center;
align-items: center;
font-size: 1.12em;
text-align: center;
padding: 0.4em 1em;
padding-top: 0.8em;
}
#calTitle button{
outline: none;
display: block;
border: 0.1em solid #ddd;
border: none;
padding: 0;
width: 40px;
height: 40px;
line-height: 60px;
border-radius: 50%;
background-color: rgba(0, 0, 0, 0.1);
}
#calTitle button svg{
width: 30px;
height: 30px;
}
#calTitle button:hover{
background: rgba(255,255,255,0.1);
}
#calThead, #calTbody{
display: flex;
flex-wrap: wrap;
padding: 0.1em;
}
#calThead{
color: #fff;
margin-top: 0.4em;
align-items: center;
text-align: center;
font-size: 0.88em;
}
#calThead > div, #calTbody .a-date{
box-sizing: border-box;
flex: 1;
min-width: calc(100% / 7);
max-width: calc(100% / 7);
width: calc(100% / 7);
text-align: center;
padding: 0;
}
#calThead > div{
font-size: 1.1em;
padding: 0.2em 0.2em;
}
#calTbody{
color: #ddd;
}
#calTbody .a-date > span{
display: block;
font-size: 1em;
}
#calTbody .a-date{
cursor: default;
padding: 0;
position: relative;
background-color: transparent;
color: inherit;
padding: 1em;
border: 0.1em solid transparent;
outline: none;
font-size: 0.9em;
}
#calTbody .a-date.blurred{
opacity: 0.5;
pointer-events: none;
}
#calTbody .a-date.event:before{
content: '';
position: absolute;
top: 0.2em;
right: 0;
left: 0;
margin: auto;
background-color: #fffc23;
width: 0.3em;
height: 0.3em;
border-radius: 50%;
}
#calTbody .a-date.current{
border-color: #fffc23;
outline: none;
outline: 0;
}
#calTbody .a-date.current.event{
background-color: #fffc23;
color: #000;
}
#calTbody .a-date:focus,
#calTbody .a-date:active{
background: #3f4042;
}
#calTFooter{
display: flex;
justify-content: space-between;
-ms-align-items: center;
align-items: center;
font-size: 1.1em;
padding: 0 1em;
margin-top: 0.5em;
}
#calTFooter #calLink{
font-size: 0.8em;
display: inline-block;
padding: 0.6em 0.8em;
flex-shrink: 0;
text-decoration: none;
color: #fffc23;
}
#calTFooter #calLink:hover{
background-color: #555;
}
#calTFooter #eventTitle{
margin: 0;
margin-right: 0.1em;
font-weight: normal;
font-size: 0.95em;
white-space: nowrap;
overflow: hidden;
-ms-text-overflow: ellipsis;
text-overflow: ellipsis;
}

highlight a current date

I am beginner for programming. I got a code from online and I am modifying to get hands on js, jquery, jsp. What I am trying to get is I need to highlight a today's date. I tried many times but could not succeeded. Any help will be greatly appreciated.
$(document).ready(function () {
var Calendar = function(calen) {
//Store div id
this.divId = calen.ParentID;
// Days of week, starting on Sunday
this.DaysOfWeek = calen.DaysOfWeek;
// Months, stating on January
this.Months = calen.Months;
// Set the current month, year
var d = new Date();
this.CurrentMonth = d.getMonth();
this.CurrentYear = d.getFullYear();
var f=calen.Format;
//this.f = typeof(f) == 'string' ? f.charAt(0).toUpperCase() : 'M';
if(typeof(f) == 'string') {
this.f = f.charAt(0).toUpperCase();
} else {
this.f = 'M';
}
};
// Goes to next month
Calendar.prototype.nextMonth = function() {
if ( this.CurrentMonth == 11 ) {
this.CurrentMonth = 0;
this.CurrentYear++;
} else {
console.log("this.CurrentMonth == ", this.CurrentMonth);
this.CurrentMonth++;
}
this.showCurrent();
};
// Goes to previous month
Calendar.prototype.previousMonth = function() {
if ( this.CurrentMonth == 0 ) {
this.CurrentMonth = 11;
this.CurrentYear--;
} else {
this.CurrentMonth--;
}
this.showCurrent();
};
//
Calendar.prototype.previousYear = function() {
this.CurrentYear--;
this.showCurrent();
}
Calendar.prototype.nextYear = function() {
this.CurrentYear++;
this.showCurrent();
}
// Show current month
Calendar.prototype.showCurrent = function() {
this.Calendar(this.CurrentYear, this.CurrentMonth);
};
// Show month (year, month)
Calendar.prototype.Calendar = function(y,m,n) {
typeof(y) == 'number' ? this.CurrentYear = y : null;
typeof(y) == 'number' ? this.CurrentMonth = m : null;
typeof(y) == 'number' ? this.CurrDate = n : null;
// 1st day of the selected month
var firstDayOfCurrentMonth = new Date(y, m, 1).getDay();
// Last date of the selected month
var lastDateOfCurrentMonth = new Date(y, m+1, 0).getDate();
// Last day of the previous month
var lastDateOfLastMonth = m == 0 ? new Date(y-1, 11, 0).getDate() : new Date(y, m, 0).getDate();
// Write selected month and year. This HTML goes into <div id="year"></div>
//var yearhtml = '<span class="yearspan">' + y + '</span>';
// Write selected month and year. This HTML goes into <div id="month"></div>
//var monthhtml = '<span class="monthspan">' + this.Months[m] + '</span>';
// Write selected month and year. This HTML goes into <div id="month"></div>
var monthandyearhtml = '<span id="monthandyearspan">' + this.Months[m] + ' - ' + y + '</span>';
var html = '<table>';
// Write the header of the days of the week
html += '<tr>';
for(var i=0; i < 7;i++) {
html += '<th class="daysheader">' + this.DaysOfWeek[i] + '</th>';
}
html += '</tr>';
//this.f = 'X';
var p = dm = this.f == 'M' ? 1 : (firstDayOfCurrentMonth == 0 ? -5 : 2);
var cellvalue;
for (var d, i=0, z=0; z<6; z++) {
html += '<tr>';
for (var k= 0; k < 7; k++) {
d = i + dm - firstDayOfCurrentMonth;
// Dates from prev month
if (d < 1){
cellvalue = lastDateOfLastMonth - firstDayOfCurrentMonth + p++;
html += '<td id="prevmonthdates">' +
'<span id="cellvaluespan">' + (cellvalue) + '</span><br/>' +
'</td>';
// Dates from next month
} else if ( d > lastDateOfCurrentMonth){
html += '<td id="nextmonthdates">' + (p++) + '</td>';
// Current month dates
} else {
html += '<td id="currentmonthdates">' + (d) + '</td>';
p = 1;
}
if (i % 7 == 6 && d >= lastDateOfCurrentMonth) {
z = 10; // no more rows
}
i++;
}
html += '</tr>';
}
// Closes table
html += '</table>';
document.getElementById("monthandyear").innerHTML = monthandyearhtml;
document.getElementById(this.divId).innerHTML = html;
};
// On Load of the window
window.onload = function() {
// Start calendar
var c = new Calendar({
ParentID:"divcalendartable",
DaysOfWeek:[
'MON',
'TUE',
'WED',
'THU',
'FRI',
'SAT',
'SUN'
],
Months:['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ],
Format:'dd/mm/yyyy'
});
c.showCurrent();
// Bind next and previous button clicks
getId('btnPrev').onclick = function(){
c.previousMonth();
};
getId('btnPrevYr').onclick = function(){
c.previousYear();
};
getId('btnNext').onclick = function(){
c.nextMonth();
};
getId('btnNextYr').onclick = function(){
c.nextYear();
};
}
// Get element by id
function getId(id) {
return document.getElementById(id);
}
});
html, body { margin: 0; padding: 0; }
table {
border-collapse: collapse;
font-family: Georgia, Times, serif;
}
th {
border: 1px solid #A8A8A8;
vertical-align: top;
}
td {
height: 150px;
width: 150px;
padding: 10px;
border: 1px solid #A8A8A8;
vertical-align: top;
text-align:center;
}
.divcalendar {
padding: 15px;
float:left;
/*background-color: #FFCC00;*/
}
/* Wrapper div. That makes the inner div into an inline element that can be centered with text-align.*/
#calendaroverallcontrols {
text-align: center;
}
/* This is a fluid div as width will be changing */
#calendarmonthcontrols {
display: inline-block;
/*background-color: #FF0000;*/
}
#calendarmonthcontrols > div, #calendarmonthcontrols > a {
display: inline-block;
}
#btnPrevYr {
text-decoration: none;
font-size: 35px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#btnPrev {
text-decoration: none;
font-size: 35px;
margin-left: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
/*.yearspan {
font-size: 20px;
font-weight: bold;
float: left;
margin-left: 5px;
margin-right: 5px;
}
.monthspan {
font-size: 20px;
font-weight: bold;
float: left;
margin-left: 5px;
margin-right: 5px;
}*/
#monthandyearspan {
width: 50px;
font-size: 25px;
font-weight: bold;
margin-left: 20px;
margin-right: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#monthandyear {
vertical-align: middle;
}
#btnNext {
text-decoration: none;
font-size: 35px;
margin-right: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#btnNextYr {
text-decoration: none;
font-size: 35px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#divcalendartable {
clear: both;
}
.daysheader {
background: #C0C0C0;
height: auto;
text-align: center;
}
#prevmonthdates {
background-color: #E0E0E0;
}
#nextmonthdates {
background-color: #E0E0E0;
}
#currentmonthdates {
background-color: #FFFFFF;
}
#cellvaluespan {
background: #FF0000;
}
#cellvaluelist {
background: #FFCC00;
}
.swim {
font-family: Arial, Helvetica, sans-serif;
font-size: 80%;
text-align: center;
background: #445511;
color: #F5F5F5;
margin-bottom: 5px;
padding: 5px;
}
.chrono {
font-family: Arial, Helvetica, sans-serif;
font-size: 80%;
text-align: center;
background: #778899;
color: #F5F5F5;
margin-bottom: 5px;
padding: 5px;
}
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<div class="divcalendar">
<div id="calendaroverallcontrols">
<div id="calendarmonthcontrols">
<a id="btnPrevYr" href="#" title="Previous Year"><span></span></a>
<a id="btnPrev" href="#" title="Previous Month"><span><</span></a>
<div id="monthandyear"></div>
<a id="btnNext" href="#" title="Next Month"><span>></span></a>
<a id="btnNextYr" href="#" title="Next Year"><span></span></a>
</div>
</div>
<!-- extra -->
<div id="divcalendartable"></div>
</div>
Introduction: you don't need at all jQuery. Avoid to insert into jQuery Dom ready event the window.onload. It's useless.
The fast way to achieve your goal is:
Define a new css class:
.currentDay {
background-color: green !important;
}
In the method "Calendar.prototype.Calendar = function (y, m, n) {" change these lines:
// Current month dates
} else {
html += '<td id="currentmonthdates">' + (d) + '</td>';
p = 1;
}
with:
} else {
var lDate = new Date();
if (d == lDate.getDate() && this.CurrentMonth == lDate.getMonth() &&
this.CurrentYear == lDate.getFullYear()) {
html += '<td id="currentmonthdates" class="currentDay">' + (d) + '</td>';
} else {
html += '<td id="currentmonthdates">' + (d) + '</td>';
}
p = 1;
}
The previous change adds the class currentDay to today.
var Calendar = function (calen) {
//Store div id
this.divId = calen.ParentID;
// Days of week, starting on Sunday
this.DaysOfWeek = calen.DaysOfWeek;
// Months, stating on January
this.Months = calen.Months;
// Set the current month, year
var d = new Date();
this.CurrentMonth = d.getMonth();
this.CurrentYear = d.getFullYear();
var f = calen.Format;
//this.f = typeof(f) == 'string' ? f.charAt(0).toUpperCase() : 'M';
if (typeof(f) == 'string') {
this.f = f.charAt(0).toUpperCase();
} else {
this.f = 'M';
}
};
// Goes to next month
Calendar.prototype.nextMonth = function () {
if (this.CurrentMonth == 11) {
this.CurrentMonth = 0;
this.CurrentYear++;
} else {
console.log("this.CurrentMonth == ", this.CurrentMonth);
this.CurrentMonth++;
}
this.showCurrent();
};
// Goes to previous month
Calendar.prototype.previousMonth = function () {
if (this.CurrentMonth == 0) {
this.CurrentMonth = 11;
this.CurrentYear--;
} else {
this.CurrentMonth--;
}
this.showCurrent();
};
Calendar.prototype.previousYear = function () {
this.CurrentYear--;
this.showCurrent();
}
Calendar.prototype.nextYear = function () {
this.CurrentYear++;
this.showCurrent();
}
// Show current month
Calendar.prototype.showCurrent = function () {
this.Calendar(this.CurrentYear, this.CurrentMonth);
};
// Show month (year, month)
Calendar.prototype.Calendar = function (y, m, n) {
typeof(y) == 'number' ? this.CurrentYear = y : null;
typeof(y) == 'number' ? this.CurrentMonth = m : null;
typeof(y) == 'number' ? this.CurrDate = n : null;
// 1st day of the selected month
var firstDayOfCurrentMonth = new Date(y, m, 1).getDay();
// Last date of the selected month
var lastDateOfCurrentMonth = new Date(y, m + 1, 0).getDate();
// Last day of the previous month
var lastDateOfLastMonth = m == 0 ? new Date(y - 1, 11, 0).getDate() : new Date(y, m, 0).getDate();
// Write selected month and year. This HTML goes into <div id="year"></div>
//var yearhtml = '<span class="yearspan">' + y + '</span>';
// Write selected month and year. This HTML goes into <div id="month"></div>
//var monthhtml = '<span class="monthspan">' + this.Months[m] + '</span>';
// Write selected month and year. This HTML goes into <div id="month"></div>
var monthandyearhtml = '<span id="monthandyearspan">' + this.Months[m] + ' - ' + y + '</span>';
var html = '<table>';
// Write the header of the days of the week
html += '<tr>';
for (var i = 0; i < 7; i++) {
html += '<th class="daysheader">' + this.DaysOfWeek[i] + '</th>';
}
html += '</tr>';
//this.f = 'X';
var p = dm = this.f == 'M' ? 1 : (firstDayOfCurrentMonth == 0 ? -5 : 2);
var cellvalue;
for (var d, i = 0, z = 0; z < 6; z++) {
html += '<tr>';
for (var k = 0; k < 7; k++) {
d = i + dm - firstDayOfCurrentMonth;
// Dates from prev month
if (d < 1) {
cellvalue = lastDateOfLastMonth - firstDayOfCurrentMonth + p++;
html += '<td id="prevmonthdates">' +
'<span id="cellvaluespan">' + (cellvalue) + '</span><br/>' +
'</td>';
// Dates from next month
} else if (d > lastDateOfCurrentMonth) {
html += '<td id="nextmonthdates">' + (p++) + '</td>';
// Current month dates
} else {
var lDate = new Date();
if (d == lDate.getDate() && this.CurrentMonth == lDate.getMonth() && this.CurrentYear == lDate.getFullYear()) {
html += '<td id="currentmonthdates" class="currentDay">' + (d) + '</td>';
} else {
html += '<td id="currentmonthdates">' + (d) + '</td>';
}
p = 1;
}
if (i % 7 == 6 && d >= lastDateOfCurrentMonth) {
z = 10; // no more rows
}
i++;
}
html += '</tr>';
}
// Closes table
html += '</table>';
document.getElementById("monthandyear").innerHTML = monthandyearhtml;
document.getElementById(this.divId).innerHTML = html;
};
// On Load of the window
window.onload = function () {
// Start calendar
var c = new Calendar({
ParentID: "divcalendartable",
DaysOfWeek: [
'MON',
'TUE',
'WED',
'THU',
'FRI',
'SAT',
'SUN'
],
Months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
Format: 'dd/mm/yyyy'
});
c.showCurrent();
// Bind next and previous button clicks
getId('btnPrev').onclick = function () {
c.previousMonth();
};
getId('btnPrevYr').onclick = function () {
c.previousYear();
};
getId('btnNext').onclick = function () {
c.nextMonth();
};
getId('btnNextYr').onclick = function () {
c.nextYear();
};
// Get element by id
function getId(id) {
return document.getElementById(id);
}
}
html, body {
margin: 0;
padding: 0;
}
table {
border-collapse: collapse;
font-family: Georgia, Times, serif;
}
th {
border: 1px solid #A8A8A8;
vertical-align: top;
}
td {
height: 150px;
width: 150px;
padding: 10px;
border: 1px solid #A8A8A8;
vertical-align: top;
text-align: center;
}
.divcalendar {
padding: 15px;
float: left;
/*background-color: #FFCC00;*/
}
/* Wrapper div. That makes the inner div into an inline element that can be centered with text-align.*/
#calendaroverallcontrols {
text-align: center;
}
/* This is a fluid div as width will be changing */
#calendarmonthcontrols {
display: inline-block;
/*background-color: #FF0000;*/
}
#calendarmonthcontrols > div, #calendarmonthcontrols > a {
display: inline-block;
}
#btnPrevYr {
text-decoration: none;
font-size: 35px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#btnPrev {
text-decoration: none;
font-size: 35px;
margin-left: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
/*.yearspan {
font-size: 20px;
font-weight: bold;
float: left;
margin-left: 5px;
margin-right: 5px;
}
.monthspan {
font-size: 20px;
font-weight: bold;
float: left;
margin-left: 5px;
margin-right: 5px;
}*/
#monthandyearspan {
width: 50px;
font-size: 25px;
font-weight: bold;
margin-left: 20px;
margin-right: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#monthandyear {
vertical-align: middle;
}
#btnNext {
text-decoration: none;
font-size: 35px;
margin-right: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#btnNextYr {
text-decoration: none;
font-size: 35px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#divcalendartable {
clear: both;
}
.daysheader {
background: #C0C0C0;
height: auto;
text-align: center;
}
#prevmonthdates {
background-color: #E0E0E0;
}
#nextmonthdates {
background-color: #E0E0E0;
}
#currentmonthdates {
background-color: #FFFFFF;
}
#cellvaluespan {
background: #FF0000;
}
#cellvaluelist {
background: #FFCC00;
}
.swim {
font-family: Arial, Helvetica, sans-serif;
font-size: 80%;
text-align: center;
background: #445511;
color: #F5F5F5;
margin-bottom: 5px;
padding: 5px;
}
.chrono {
font-family: Arial, Helvetica, sans-serif;
font-size: 80%;
text-align: center;
background: #778899;
color: #F5F5F5;
margin-bottom: 5px;
padding: 5px;
}
.currentDay {
background-color: green !important;
}
<div class="divcalendar">
<div id="calendaroverallcontrols">
<div id="calendarmonthcontrols">
<a id="btnPrevYr" href="#" title="Previous Year"><span></span></a>
<a id="btnPrev" href="#" title="Previous Month"><span><</span></a>
<div id="monthandyear"></div>
<a id="btnNext" href="#" title="Next Month"><span>></span></a>
<a id="btnNextYr" href="#" title="Next Year"><span></span></a>
</div>
</div>
<!-- extra -->
<div id="divcalendartable"></div>
</div>
I guess you need to include jQuery.js.
https://learn.jquery.com/using-jquery-core/document-ready/

Using JQuery to increase input by 1 limiting to 9 and concatenating to hidden input

Trying to use plus/minus to increase/decrease numbers by 0-9 then continually concatenate the input values to one hidden input that will be submitted into the CMS.
JSFiddle is here and currently can't limit numbers and unable to concatenate the values.
https://jsfiddle.net/c06sy673/2/
//Script for concatinating counter1 and counter2
$(document).click(function() {
var value1 = $('.counter1').val();
var value2 = $('.counter2').val();
$(".output").val(value1 + value2);
});
//Script for increasing value increment by +1 and preventing numbers below 0
$(function() {
$("form .counter-inner").append('<div class="inc increment_button">+</div><div class="dec increment_button">-</div>');
$(".increment_button").on("click", function() {
var $button = $(this);
var oldValue = $button.parent().find("input").val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
}
$button.parent().find("input").val(newVal);
});
});
.counter-wrapper {
position: relative;
width: 480px;
display: inline-block;
}
.inc {
position: absolute;
top: 22px;
left: 50%;
margin-left: -15px;
font-size: 60px;
line-height: 0px;
}
.dec {
position: absolute;
bottom: 32px;
left: 50%;
margin-left: -12px;
font-size: 90px;
line-height: 0px;
}
.counter {
-webkit-appearance: none;
-webkit-rtl-ordering: logical;
-webkit-user-select: text;
cursor: auto;
font-size: 130px;
width: 187px;
text-align: center;
margin-left: 0px;
margin-top: 60px;
margin-bottom: 60px;
border: 1px solid black;
padding: 50px 0px;
height: 280px;
color: white;
background-color: black;
font-weight: 700;
}
.increment_button {
cursor: pointer;
}
.counter-inner {
display: inline-block;
position: relative;
}
<form method="post" action="">
<div class="counter-wrapper">
<label for="name">Team 1</label>
<div class="counter-inner">
<input type="text" name="team_1--count1 increment" class="counter counter1" value="0">
</div>
<div class="counter-inner">
<input type="text" name="team_1--count2 increment" class="counter counter2" value="0">
</div>
</div>
<div class="counter-wrapper">
<label for="name">Team 1</label>
<div class="counter-inner">
<input type="text" name="team_1--count1 increment" class="counter counter3" value="0">
</div>
<div class="counter-inner">
<input type="text" name="team_1--count2 increment" class="counter counter4" value="0">
</div>
</div>
<input type="submit" value="Submit" id="submit">
</form>
<p class="output"></p>
Apologies in advance if I'm just missing something really obvious!
This is what you want:
https://jsfiddle.net/c06sy673/6/
//Script for concatinating counter1 and counter2
$(document).click(function () {
var value1 = $('.counter1').val();
var value2 = $('.counter2').val();
$(".output").text(value1 + value2);
});
//Script for increasing value increment by +1 and preventing numbers below 0
$(function () {
$("form .counter-inner").append('<div class="inc increment_button">+</div><div class="dec increment_button">-</div>');
$(".increment_button").on("click", function () {
var $button = $(this);
var oldValue = $button.parent().find("input").val();
if ($button.text() == "+") {
if(oldValue < 9){
var newVal = parseFloat(oldValue) + 1;
}else{
var newVal = parseFloat(oldValue);
}
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
}
$button.parent().find("input").val(newVal);
});
});
Simply change your
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
}
to
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) < 9 ? parseFloat(oldValue) + 1 : parseFloat(oldValue);
}
jsFiddle
replace
var newVal = parseFloat(oldValue) + 1;
whit
var temp = parseFloat(oldValue) + 1;
newVal=temp<=9?temp:9;
this should limit the number to 9.
but i am not sure what do you mean by "concatenate the values".

Categories

Resources