WooCommerce html / java form to calculate price - javascript

I have an HTML / JAVA form that calculates a net price. With a click on the button, the product with the calculated price and the number of motifs should be packed into the shopping cart and an e-mail with the file and the number of motifs should be sent to me. Who can help me to solve the problem?
Script:
`<div style="width: 100%; display: flex;flex-wrap: wrap;" id="plugin-container">
<div class="plugin-box plugin-item" style="width: 100%;height: 700px;border: 0px dashed rgb(90, 183, 169);margin: 3px;padding: 10px;max-width: 90%;">
<table>
<tr>
<td>
Datei:
</td>
<td>
<input type="file" name="file[]" accept="application/pdf, image/png, image/gif, image/jpeg, .eps, .ai" />
</td>
</tr>
<tr>
<td colspan="2">
 
</td>
</tr>
<tr>
<td colspan="2">
Motivmaße angeben:
</td>
</tr>
<tr>
<td>
Breite:
</td>
<td>
<input required="" min="0" type="number" class="input-b" name="b[]" placeholder="in cm" onchange="exec_computation(this.closest('.plugin-box'))" onkeyup="exec_computation(this.closest('.plugin-box'))" />
</td>
</tr>
<tr>
<td>
Höhe:
</td>
<td>
<input required="" min="0" type="number" class="input-h" name="h[]" placeholder="in cm" onchange="exec_computation(this.closest('.plugin-box'))" onkeyup="exec_computation(this.closest('.plugin-box'))" />
</td>
</tr>
<tr>
<td colspan="2">
 
</td>
</tr>
<tr>
<td>
Anzahl Motive:
</td>
<td>
<input required="" min="0" step="1" type="number" class="input-m" name="m[]" onchange="exec_computation(this.closest('.plugin-box'))" onkeyup="exec_computation(this.closest('.plugin-box'))" />
</td>
</tr>
</table>
<div class="plugin-result" style="margin-top: 20px;">
</div>
<input type="hidden" class="input-size" name="sizes[]" value="0" />
</div>
<button type="button">Click Me!</button>
</div>
</form>
<script type="text/javascript">
//<![CDATA[
const alg = (h, b, m, r, z, p, s) => {
if (b > (z - 2 * r) && h > (z - 2 * r)) {
// Does not fit at all
//document.getElementById("result").innerHTML = 'Diese Maße können nicht gedruckt werden.'
return -1;
}
const max_0 = Math.floor(z / b) * (b + 2 * r) <= z ? Math.floor(z / b) : Math.floor(z / b) - Math.ceil((Math.floor(z / b) * (b + 2 * r) - z) / (b + 2 * r));
const max_90 = Math.floor(z / h) * (h + 2 * r) <= z ? Math.floor(z / h) : Math.floor(z / h) - Math.ceil((Math.floor(z / h) * (h + 2 * r) - z) / (h + 2 * r));
const size_0 = max_0 > 0 ? (h + 2 * r) * Math.ceil(m / max_0) : Number.MAX_SAFE_INTEGER;
const size_90 = max_90 > 0 ? (b + 2 * r) * Math.ceil(m / max_90) : Number.MAX_SAFE_INTEGER;
const size = Math.min(size_0, size_90);
//document.getElementById("result").innerHTML += 'Die Ausrichtung ist ' + (size_0 <= size_90 ? 'normal' : 'hochkant') + '<br />';
//document.getElementById("result").innerHTML += 'Laufmeter: ' + (Math.round((size + Number.EPSILON) * 100) / 100).toString() + '<br />';
const cost_netto = size * p;
const cost_brutto = cost_netto * 1.19;
const formatter = new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' });
//document.getElementById("result").innerHTML += 'Kosten netto: ' + formatter.format(cost_netto) + '<br />';
//document.getElementById("result").innerHTML += 'Kosten brutto: ' + formatter.format(cost_brutto) + '<br />';
//document.getElementById("result").innerHTML += 'Versandkosten: ' + formatter.format(shipping()) + '<br />';
return {
size: (Math.round((size + Number.EPSILON) * 100) / 100),
costNetto: cost_netto,
costBrutto: cost_brutto,
m: m
};
};
const compute = () => {
alg(
Number(document.getElementsByName("h[]")[0].value) / 100,
Number(document.getElementsByName("b[]")[0].value) / 100,
Number(document.getElementsByName("m[]")[0].value),
0.005,
0.55,
10,
"DE"
)
};
const exec_computation = (elem) => {
if (
Number(elem.querySelectorAll(".input-h")[0].value) !== 0 &&
Number(elem.querySelectorAll(".input-b")[0].value) !== 0 &&
Number(elem.querySelectorAll(".input-m")[0].value) !== 0
) {
const result = alg(
Number(elem.querySelectorAll(".input-h")[0].value) / 100,
Number(elem.querySelectorAll(".input-b")[0].value) / 100,
Number(elem.querySelectorAll(".input-m")[0].value),
0.005,
0.55,
10,
"DE"
);
if (result === -1) {
elem.querySelectorAll(".plugin-result")[0].innerHTML = '<span style="color: red;">Diese Maße können wir leider aktuell nicht ausliefern.<\/span>';
elem.querySelectorAll(".input-size")[0].value = "-1";
} else {
const formatter = new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' });
elem.querySelectorAll(".plugin-result")[0].innerHTML = '<h4>Errechnete Drucklänge: ' + Math.floor(result.size * 100).toString() + ' cm<br />Errechneter Nettopreis: ' + formatter.format(result.size * 10) + '<br />Nettopreis pro Motiv: ' + formatter.format(result.size * 10 / result.m) + '<\/h4>';
elem.querySelectorAll(".input-size")[0].value = result.size.toString();
}
update_costs();
}
};
const plugin_delete = (elem) => {
const parent = elem.parentElement;
parent.parentElement.removeChild(parent);
};
const plugin_add = () => {
const list = document.querySelectorAll(".plugin-item:not(.plugin-new)");
let node = document.createElement("div");
node.classList.add("plugin-box", "plugin-item");
node.style.width = "400px";
node.style.height = "350px";
node.style.border = "3px dashed rgb(90, 183, 169)";
node.style.margin = "3px";
node.style.padding = "10px";
node.style.maxWidth = "100%";
node.innerHTML = '<div style="float: right;cursor: pointer;color: rgb(90, 183, 169);" onclick="plugin_delete(this);"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash3-fill" viewBox="0 0 16 16">\n' +
' <path d="M11 1.5v1h3.5a.5.5 0 0 1 0 1h-.538l-.853 10.66A2 2 0 0 1 11.115 16h-6.23a2 2 0 0 1-1.994-1.84L2.038 3.5H1.5a.5.5 0 0 1 0-1H5v-1A1.5 1.5 0 0 1 6.5 0h3A1.5 1.5 0 0 1 11 1.5Zm-5 0v1h4v-1a.5.5 0 0 0-.5-.5h-3a.5.5 0 0 0-.5.5ZM4.5 5.029l.5 8.5a.5.5 0 1 0 .998-.06l-.5-8.5a.5.5 0 1 0-.998.06Zm6.53-.528a.5.5 0 0 0-.528.47l-.5 8.5a.5.5 0 0 0 .998.058l.5-8.5a.5.5 0 0 0-.47-.528ZM8 4.5a.5.5 0 0 0-.5.5v8.5a.5.5 0 0 0 1 0V5a.5.5 0 0 0-.5-.5Z"/>\n' +
'<\/svg><\/div><table>\n' +
' <tr>\n' +
' <td>Datei:<\/td>\n' +
' <td><input type="file" name="file[]" accept="application/pdf, image/png, image/gif, image/jpeg, .eps, .ai" /><\/td>\n' +
' <\/tr>\n' +
' <tr>\n' +
' <td colspan="2"> <\/td>\n' +
' <\/tr>\n' +
' <tr>\n' +
' <td colspan="2">Motivmaße angeben:<\/td>\n' +
' <\/tr>\n' +
' <tr>\n' +
' <td>Breite:<\/td>\n' +
' <td><input required min="0" type="number" class="input-b" name="b[]" placeholder="in cm" onchange="exec_computation(this.closest(\'.plugin-box\'))" onkeyup="exec_computation(this.closest(\'.plugin-box\'))" /><\/td>\n' +
' <\/tr>\n' +
' <tr>\n' +
' <td>Höhe:<\/td>\n' +
' <td><input required min="0" type="number" class="input-h" name="h[]" placeholder="in cm" onchange="exec_computation(this.closest(\'.plugin-box\'))" onkeyup="exec_computation(this.closest(\'.plugin-box\'))" /><\/td>\n' +
' <\/tr>\n' +
' <tr>\n' +
' <td colspan="2"> <\/td>\n' +
' <\/tr>\n' +
' <tr>\n' +
' <td>Anzahl Motive:<\/td>\n' +
' <td><input required min="0" step="1" type="number" class="input-m" name="m[]" onchange="exec_computation(this.closest(\'.plugin-box\'))" onkeyup="exec_computation(this.closest(\'.plugin-box\'))" /><\/td>\n' +
' <\/tr>\n' +
'\n' +
' <\/table>\n' +
' <div class="plugin-result" style="margin-top: 20px;">\n' +
'\n' +
' <\/div>\n' +
' <input type="hidden" class="input-size" name="sizes[]" value="0" />' +
'';
list[list.length - 1].after(node);
};
const update_costs = () => {
let size_sum = 0;
let content = '<table>';
const formatter = new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' });
document.querySelectorAll(".input-size").forEach((elem) => {
size_sum += Number(elem.value);
});
if (size_sum > 0) {
size_sum = (Math.round((size_sum + Number.EPSILON) * 100) / 100);
}
const costs_netto = size_sum * 10;
const costs_brutto = costs_netto * 1.19;
let costs2_netto = 0;
let costs2_brutto = 0;
if (document.getElementById("printing").checked) {
let total_number = 0;
document.querySelectorAll(".input-m").forEach((elem) => {
total_number += Number(elem.value);
});
costs2_netto = 0.5 * total_number;
costs2_brutto = costs2_netto * 1.19;
}
const s = document.getElementById("select-country").value;
const shipping_netto = () => {
if ((size_sum >= 5 && s === "DE") || document.getElementById("printing").checked) {
return 0;
}
if (s === "DE") {
return 7;
}
return 99;
};
const shipping_brutto = shipping_netto() * 1.19;
content += 'Bedruckte Drucklänge gesamt: ' + Math.floor(size_sum * 100).toString() + ' cm<br />';
content += 'Druckpreis netto: ' + formatter.format(costs_netto) + '<br />';
if (document.getElementById("printing").checked) {
content += 'Druckservice netto: ' + formatter.format(costs2_netto) + '<br />';
content += 'Versand wird nachträglich pro Karton berechnet<br />';
} else {
content += 'Versand netto: ' + formatter.format(shipping_netto()) + '<br />';
}
content += '<h3 style="font-size: 1.2em;">Gesamtpreis brutto (inkl. 19% MwSt.): ' + formatter.format(costs_brutto + costs2_brutto + shipping_brutto) + '<\/h3><br />';
document.getElementById("plugin-total").innerHTML = content;
if (size_sum > 0 && document.getElementById("agb").checked) {
document.getElementById("plugin-button").disabled = false;
document.getElementById("plugin-button").style.background = "#1CA594";
document.getElementById("plugin-button").style.border = "2px solid #1CA594";
} else {
document.getElementById("plugin-button").disabled = true;
document.getElementById("plugin-button").style.background = "#AAA";
document.getElementById("plugin-button").style.border = "2px solid #AAA";
}
};
const changeAddressRows = () => {
if (!document.getElementById("address").checked) {
document.querySelectorAll(".plugin-address-row").forEach((elem) => {
elem.style.display = "table-row";
});
} else {
document.querySelectorAll(".plugin-address-row").forEach((elem) => {
elem.style.display = "none";
});
}
};
<button type="button">Click Me!</button>`
I dont know how to solve this problem.

Related

Why can't I calculate percentage discount from this HTML table in JS?

As a beginner, I've been trying to get this to 01) generate the discount value; 02) Calculate the resulting value, as the user informs the percentage, but it gives me number as type, then NaN right after it.
function grand_total(el) {
let grandTotal = 0;
let termsTotal = 0;
let dollarUS = Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
});
if (el) {
let total = 0;
total += parseFloat(document.getElementById('totalValue').innerText);
console.log('Type Total: ' + typeof total);
console.log(total);
let percentage = 0;
percentage += parseInt(el.value);
console.log('Percentage: ' + JSON.stringify(percentage))
console.log('Percentage Type: ' + typeof percentage)
if (percentage > 0) {
termsTotal = (percentage / 100) * total;
grandTotal = total - termsTotal;
}
console.log('Terms Total: ' + JSON.stringify(termsTotal))
console.log('Grand Total: ' + JSON.stringify(grandTotal))
document.getElementById('termsTotal').innerText = termsTotal
document.getElementById('grandTotal').innerText = grandTotal
}
}
<table class="table table-hover table-vcenter" id="dtable">
<tr>
<td id="totalTitle" colspan="10" align="right"><strong>Total:</strong></td>
<td id="totalValue" class="total">$7.75</td>
</tr>
<tr>
<td id="termsRow" colspan="9" align="right"><strong>Deposit(%):</strong></td>
<td><input type="number" min="0" class="terms" name="numberInputs" value="30" onchange="grand_total(this)"></td>
<td id="termsTotal" class="terms_total">NaN</td>
</tr>
<tr>
<td id="grandTotalRow" colspan="10" align="right"><strong>Grand Total:</strong></td>
<td id="grandTotal" class="grand_total">NaN</td>
</tr>
</table>
Apperciate any help.
You need to strip the dollar sign out of the text you are trying to convert to a number first. You can do that with Number(document.getElementById('totalValue').innerText.replace(/[^0-9.-]+/g,''));
function grand_total(el) {
let grandTotal = 0;
let termsTotal = 0;
let dollarUS = Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
});
if (el) {
let totalValue = Number(document.getElementById('totalValue').innerText.replace(/[^0-9.-]+/g,''));
let total = 0;
total += parseFloat(totalValue);
console.log('Type Total: ' + typeof total);
console.log(total);
let percentage = 0;
percentage += parseInt(el.value);
console.log('Percentage: ' + JSON.stringify(percentage))
console.log('Percentage Type: ' + typeof percentage)
if (percentage > 0) {
termsTotal = (percentage / 100) * total;
grandTotal = total - termsTotal;
}
console.log('Terms Total: ' + JSON.stringify(termsTotal))
console.log('Grand Total: ' + JSON.stringify(grandTotal))
document.getElementById('termsTotal').innerHTML = termsTotal
document.getElementById('grandTotal').innerHTML = grandTotal
}
}
document.querySelector('.terms').addEventListener('change',function(){
grand_total(this);
});
<table>
<tr>
<td id="totalValue" class="total">$17.75</td>
<td><input type="number" min="0" class="terms" name="numberInputs" value="30" /></td>
<td id="termsTotal" class="terms_total"><strong></strong></td>
<td id="grandTotal" class="grand_total"><strong></strong></td>
</tr>
</table>
First change td tag to span or div element as td is a part of table tag and remove "$"
function grand_total(el) {
let grandTotal = 0;
let termsTotal = 0;
let dollarUS = Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
});
if (el) {
let total = 0;
total += parseFloat(document.getElementById("totalValue").innerText);
console.log("Type Total: " + typeof total);
console.log(total);
let percentage = 0;
percentage += parseInt(el.value);
console.log("Percentage: " + JSON.stringify(percentage));
console.log("Percentage Type: " + typeof percentage);
if (percentage > 0) {
termsTotal = (percentage / 100) * total;
grandTotal = total - termsTotal;
}
console.log("Terms Total: " + JSON.stringify(termsTotal));
console.log("Grand Total: " + JSON.stringify(grandTotal));
document.getElementById("termsTotal").innerHTML = termsTotal;
document.getElementById("grandTotal").innerHTML = grandTotal;
}
}
<span id="totalValue" class="total">17.75</span>
<input
type="number"
min="0"
class="terms"
name="numberInputs"
value="30"
onchange="grand_total(this)"
/>
<br />
<span id="termsTotal" class="terms_total"><strong></strong></span>
<br />
<span id="grandTotal" class="grand_total"><strong></strong></span>

Add alt and title tags to images with the help of JavaScript

I have this script that uses the blogger feed to pull the content.
It pulls text and image from the article.
It would be perfect if the Alt and Title tags were added to the images, does anyone have any idea how to do this?
<div id="feed-list-container">
</div>
<div style="clear:both;">
</div>
<style>
div[data-tag=''] {float: left;
positon: relative;
width: 26%;
background-color: #9cb5c2;
}
</style>
<script type='text/javascript'>
var multiFeed = {
feedsUri: [
{
name: "Terror",
url: "https://elfenliedbrazil.blogspot.com/",
tag: "Terror"
},
],
numPost: 18,
showThumbnail: true,
showSummary: true,
summaryLength: 200,
titleLength:"auto",
thumbSize: 200,
containerId: "feed-list-container",
readMore: {
text: "",
endParam: "?max-results=20"
}
};
</script>
This is my code so far:
var mf_defaults = {
feedsUri: [{
name: "Posting JQuery",
url: " ",
tag: "JQuery"
}, {
name: "Posting CSS",
url: "",
tag: "CSS"
}, {
name: "Widget-Widget Blogger",
url: " ",
tag: "Widget"
}],
numPost: 4,
showThumbnail: true,
showSummary: true,
summaryLength: 80,
titleLength: "auto",
thumbSize: 200,
thumbWidth: 200, // new setting
thumbHeight: 90, // new setting
newTabLink: false,
containerId: "feed-list-container",
listClass: "list-entries",
readMore: {
text: "More",
endParam: "?max-results=20"
},
autoHeight: false,
current: 0,
onLoadFeed: function(a) {},
onLoadComplete: function() {},
loadFeed: function(c) {
var d = document.getElementsByTagName("head")[0],
a = document.getElementById(this.containerId),
b = document.createElement("script");
b.type = "text/javascript";
b.src = this.feedsUri[c].url + "/feeds/posts/summary" + (this.feedsUri[c].tag ? "/-/" + this.feedsUri[c].tag : "") + "?alt=json-in-script&max-results=" + this.numPost + "&callback=listEntries";
d.appendChild(b)
}
};
for(var i in mf_defaults) {
mf_defaults[i] = (typeof(multiFeed[i]) !== undefined && typeof(multiFeed[i]) !== "undefined") ? multiFeed[i] : mf_defaults[i]
}
function listEntries(q) {
var p = q.feed.entry,
c = mf_defaults,
h = document.getElementById(c.containerId),
a = document.createElement("div"),
d = "",
l = c.feedsUri.length,
n, k, m, g;
for(var f = 0; f < c.numPost; f++) {
if(f == p.length) {
break
}
n = (c.titleLength !== "auto") ? p[f].title.$t.substring(0, c.titleLength) + (c.titleLength < p[f].title.$t.length ? "…" : "") : p[f].title.$t;
m = ("summary" in p[f]) ? p[f].summary.$t.replace(/<br ?\/?>/g, " ").replace(/<.*?>/g, "").replace(/[<>]/g, "") : "";
m = (c.summaryLength < m.length) ? m.substring(0, c.summaryLength) + "…" : m;
g = ("media$thumbnail" in p[f]) ? '<img src="' + p[f].media$thumbnail.url.replace(/\/s72(\-c)?\//, "/w" + c.thumbWidth + "-h" + c.thumbHeight + "-c/") + '" style="width:' + c.thumbWidth + "px;height:" + c.thumbHeight + 'px;">' : '';
for(var e = 0, b = p[f].link.length; e < b; e++) {
k = (p[f].link[e].rel == "alternate") ? p[f].link[e].href : "#"
}
d += '<div data-tag="'+c.feedsUri[c.current].tag+'" class="post hentry"' + (!c.autoHeight ? ' style="height' + c.thumbHeight + 'px;overflow:hidden; border-width:1px; border-style: solid; border-color: #000000; height: 200px"' : "") + ">";
d += '<div class="post-title-2" style=" height: 38px;"><h2 style=" font-size: 13px; ">" + n + "</h2></div>";
d += (c.showThumbnail) ? g : "";
d += '<div class="summary">';
d += "<span" + (!c.showSummary ? ' style="display:none;"' : "") + ">";
d += (c.showSummary) ? m : "";
d += "</span></div>";
d += '<span style="display:block;clear:both;"></span></div>'
}
d += "";
d += '<div class="more-link">" + c.readMore.text + "</div>";
a.className = c.listClass;
a.innerHTML = '<div data-tag=" margin-top: -33px;'+c.feedsUri[c.current].tag+'" +class="main-title"><h2>' + c.feedsUri[c.current].name + "</h2></div>" + d;
h.appendChild(a);
c.onLoadFeed(c.current);
if((c.current + 1) < l) {
c.loadFeed(c.current + 1)
}
if((c.current + 1) == l) {
c.onLoadComplete()
}
c.current++
}
mf_defaults.loadFeed(0);
I believe that the party that is responsible for pulling the image is img
This may be a stupid answer... but from what I understand of your question, have you tried this?
g = ("media$thumbnail" in p[f]) ? '<img src="' + p[f].media$thumbnail.url.replace(/\/s72(\-c)?\//, "/w" + c.thumbWidth + "-h" + c.thumbHeight + "-c/") + '" style="width:' + c.thumbWidth + "px;height:" + c.thumbHeight + 'px;" title="' + n + '" alt="' + n + '">' : '';

Multiday Calendar Datepicker JQuery Plugin

I'm using jQuery plugin from these websites web , github.
This is screenshot whith my problem:
For some reason some months are not full ie. last day in month transfer in next month. Why?
This is JavaScript:
(function($) {
$.fn.jCal = function(opt) {
$.jCal(this, opt);
};
$.jCal = function(target, opt) {
opt = $.extend({
day : new Date(),
days : 1,
showMonths : 1,
monthSelect : false,
dCheck : function(day) {
return true;
},
callback : function(day, days) {
return true;
},
selectedBG : 'rgb(0, 143, 214)',
defaultBG : 'rgb(255, 255, 255)',
dayOffset : 0,
forceWeek : false,
dow : [ 'S', 'M', 'T', 'W', 'T', 'F', 'S' ],
ml : [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ],
ms : [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ],
_target : target
}, opt);
opt.day = new Date(opt.day.getFullYear(), opt.day.getMonth(), 1);
if (!$(opt._target).data('days')) $(opt._target).data('days', opt.days);
$(target).stop().empty();
for (var sm = 0; sm < opt.showMonths; sm++) $(target).append('<div class="jCalMo"></div>');
opt.cID = 'c' + $('.jCalMo').length;$('.jCalMo', target).each(function(ind) {
drawCalControl($(this), $.extend({}, opt, {
'ind' : ind,
'day' : new Date(new Date(opt.day.getTime()).setMonth(new Date(opt.day.getTime()).getMonth() + ind))
}));drawCal($(this), $.extend({}, opt, {
'ind' : ind,
'day' : new Date(new Date(opt.day.getTime()).setMonth(new Date(opt.day.getTime()).getMonth() + ind))
}));
});
if ($(opt._target).data('day') && $(opt._target).data('days')) reSelectDates(target, $(opt._target).data('day'), $(opt._target).data('days'), opt);
};
function drawCalControl(target, opt) {
$(target).append('<div class="jCal">' + ((opt.ind == 0) ? '<div class="left" />' : '') + '<div class="month">' + '<span class="monthYear">' + opt.day.getFullYear() + '</span>' + '<span class="monthName">' + opt.ml[opt.day.getMonth()] + '</span>' + '</div>' + ((opt.ind == (opt.showMonths - 1)) ? '<div class="right" />' : '') + '</div>');
if (opt.monthSelect) $(target).find('.jCal .monthName, .jCal .monthYear').bind('mouseover', $.extend({}, opt), function(e) {
$(this).removeClass('monthYearHover').removeClass('monthNameHover');
if ($('.jCalMask', e.data._target).length == 0) $(this).addClass($(this).attr('class') + 'Hover');
}).bind('mouseout', function() {
$(this).removeClass('monthYearHover').removeClass('monthNameHover');
}).bind('click', $.extend({}, opt), function(e) {
$('.jCalMo .monthSelector, .jCalMo .monthSelectorShadow').remove();
var monthName = $(this).hasClass('monthName'),
pad = Math.max(parseInt($(this).css('padding-left')), parseInt($(this).css('padding-left'))) || 2,
calcTop = (($(this).offset()).top - ((monthName ? e.data.day.getMonth() : 2) * ($(this).height() + 0)));
calcTop = calcTop > 0 ? calcTop : 0;
var topDiff = ($(this).offset()).top - calcTop;
$('<div class="monthSelectorShadow" style="' + 'top:' + $(e.data._target).offset().top + 'px; ' + 'left:' + $(e.data._target).offset().left + 'px; ' + 'width:' + ($(e.data._target).width() + (parseInt($(e.data._target).css('paddingLeft')) || 0) + (parseInt($(e.data._target).css('paddingRight')) || 0)) + 'px; ' + 'height:' + ($(e.data._target).height() + (parseInt($(e.data._target).css('paddingTop')) || 0) + (parseInt($(e.data._target).css('paddingBottom')) || 0)) + 'px;">' + '</div>').css('opacity', 0.01).appendTo($(this).parent());$('<div class="monthSelector" style="' + 'top:' + calcTop + 'px; ' + 'left:' + (($(this).offset()).left) + 'px; ' + 'width:' + ($(this).width() + (pad * 2)) + 'px;">' + '</div>').css('opacity', 0).appendTo($(this).parent());
for (var di = (monthName ? 0 : -2), dd = (monthName ? 12 : 3); di < dd; di++) $(this).clone().removeClass('monthYearHover').removeClass('monthNameHover').addClass('monthSelect').attr('id', monthName ? (di + 1) + '_1_' + e.data.day.getFullYear() : (e.data.day.getMonth() + 1) + '_1_' + (e.data.day.getFullYear() + di)).html(monthName ? e.data.ml[di] : (e.data.day.getFullYear() + di)).css('top', ($(this).height() * di)).appendTo($(this).parent().find('.monthSelector'));
var moSel = $(this).parent().find('.monthSelector').get(0),
diffOff = $(moSel).height() - ($(moSel).height() - topDiff);
$(moSel).css('clip', 'rect(' + diffOff + 'px ' + ($(this).width() + (pad * 2)) + 'px ' + diffOff + 'px 0px)').animate({
'opacity' : .92,
'clip' : 'rect(0px ' + ($(this).width() + (pad * 2)) + 'px ' + $(moSel).height() + 'px 0px)'
}, 'fast', function() {
$(this).parent().find('.monthSelectorShadow').bind('mouseover click', function() {
$(this).parent().find('.monthSelector').remove();$(this).remove();
});
}).parent().find('.monthSelectorShadow').animate({
'opacity' : .1
}, 'fast');$('.jCalMo .monthSelect', e.data._target).bind('mouseover mouseout click', $.extend({}, e.data), function(e) {
if (e.type == 'click') $(e.data._target).jCal($.extend(e.data, {
day : new Date($(this).attr('id').replace(/_/g, '/'))
}));else
$(this).toggleClass('monthSelectHover');
});
});
$(target).find('.jCal .left').bind('click', $.extend({}, opt), function(e) {
if ($('.jCalMask', e.data._target).length > 0) return false;
var mD = {
w : 0,
h : 0
};
$('.jCalMo', e.data._target).each(function() {
mD.w += $(this).width() + parseInt($(this).css('padding-left')) + parseInt($(this).css('padding-right'));
var cH = $(this).height() + parseInt($(this).css('padding-top')) + parseInt($(this).css('padding-bottom'));
mD.h = ((cH > mD.h) ? cH : mD.h);
});$(e.data._target).prepend('<div class="jCalMo"></div>');
e.data.day = new Date($('div[id*=' + e.data.cID + 'd_]:first', e.data._target).attr('id').replace(e.data.cID + 'd_', '').replace(/_/g, '/'));e.data.day.setDate(1);e.data.day.setMonth(e.data.day.getMonth() - 1);drawCalControl($('.jCalMo:first', e.data._target), e.data);drawCal($('.jCalMo:first', e.data._target), e.data);
if (e.data.showMonths > 1) {
$('.right', e.data._target).clone(true).appendTo($('.jCalMo:eq(' + (e.data.showMonths - 1) + ') .jCal', e.data._target));$('.left:last, .right:last', e.data._target).remove();
}
$(e.data._target).append('<div class="jCalSpace" style="width:' + mD.w + 'px; height:' + mD.h + 'px;"></div>');$('.jCalMo', e.data._target).wrapAll('<div class="jCalMask" style="clip:rect(0px ' + mD.w + 'px ' + mD.h + 'px 0px); width:' + (mD.w + (mD.w / e.data.showMonths)) + 'px; height:' + mD.h + 'px;">' + '<div class="jCalMove"></div>' + '</div>');$('.jCalMove', e.data._target).css('margin-left', ((mD.w / e.data.showMonths) * -1) + 'px').css('opacity', 0.5).animate({
marginLeft : '0px'
}, 'fast', function() {
$(this).children('.jCalMo:not(:last)').appendTo($(e.data._target));$('.jCalSpace, .jCalMask', e.data._target).empty().remove();
if ($(e.data._target).data('day')) reSelectDates(e.data._target, $(e.data._target).data('day'), $(e.data._target).data('days'), e.data);
});
});$(target).find('.jCal .right').bind('click', $.extend({}, opt), function(e) {
if ($('.jCalMask', e.data._target).length > 0) return false;
var mD = {
w : 0,
h : 0
};
$('.jCalMo', e.data._target).each(function() {
mD.w += $(this).width() + parseInt($(this).css('padding-left')) + parseInt($(this).css('padding-right'));
var cH = $(this).height() + parseInt($(this).css('padding-top')) + parseInt($(this).css('padding-bottom'));
mD.h = ((cH > mD.h) ? cH : mD.h);
});$(e.data._target).append('<div class="jCalMo"></div>');
e.data.day = new Date($('div[id^=' + e.data.cID + 'd_]:last', e.data._target).attr('id').replace(e.data.cID + 'd_', '').replace(/_/g, '/'));e.data.day.setDate(1);e.data.day.setMonth(e.data.day.getMonth() + 1);drawCalControl($('.jCalMo:last', e.data._target), e.data);drawCal($('.jCalMo:last', e.data._target), e.data);
if (e.data.showMonths > 1) {
$('.left', e.data._target).clone(true).prependTo($('.jCalMo:eq(1) .jCal', e.data._target));$('.left:first, .right:first', e.data._target).remove();
}
$(e.data._target).append('<div class="jCalSpace" style="width:' + mD.w + 'px; height:' + mD.h + 'px;"></div>');$('.jCalMo', e.data._target).wrapAll('<div class="jCalMask" style="clip:rect(0px ' + mD.w + 'px ' + mD.h + 'px 0px); width:' + (mD.w + (mD.w / e.data.showMonths)) + 'px; height:' + mD.h + 'px;">' + '<div class="jCalMove"></div>' + '</div>');$('.jCalMove', e.data._target).css('opacity', 0.5).animate({
marginLeft : ((mD.w / e.data.showMonths) * -1) + 'px'
}, 'fast', function() {
$(this).children('.jCalMo:not(:first)').appendTo($(e.data._target));$('.jCalSpace, .jCalMask', e.data._target).empty().remove();
if ($(e.data._target).data('day')) reSelectDates(e.data._target, $(e.data._target).data('day'), $(e.data._target).data('days'), e.data);
$(this).children('.jCalMo:not(:first)').removeClass('');
});
});$('.jCal', target).each(function() {
var width = $(this).parent().width() - ($('.left', this).width() || 0) - ($('.right', this).width() || 0);
$('.month', this).css('width', width).find('.monthName, .monthYear').css('width', ((width / 2) - 4));
});$(window).load(function() {
$('.jCal', target).each(function() {
var width = $(this).parent().width() - ($('.left', this).width() || 0) - ($('.right', this).width() || 0);
$('.month', this).css('width', width).find('.monthName, .monthYear').css('width', ((width / 2) - 4));
});
});
}
;
function reSelectDates(target, day, days, opt) {
var fDay = new Date(day.getTime());
var sDay = new Date(day.getTime());
for (var fC = false, di = 0, dC = days; di < dC; di++) {
var dF = $(target).find('div[id*=d_' + (sDay.getMonth() + 1) + '_' + sDay.getDate() + '_' + sDay.getFullYear() + ']');
if (dF.length > 0) {
dF.stop().addClass('selectedDay');
fC = true;
}
sDay.setDate(sDay.getDate() + 1);
}
if (fC && typeof opt.callback == 'function') opt.callback(day, days);
}
;
function drawCal(target, opt) {
for (var ds = 0, length = opt.dow.length; ds < length; ds++) {
$(target).append('<div class="dow">' + opt.dow[ds] + '</div>');
}
var fd = new Date(new Date(opt.day.getTime()).setDate(1));
var ldlm = new Date(new Date(fd.getTime()).setDate(0));
var ld = new Date(new Date(new Date(fd.getTime()).setMonth(fd.getMonth() + 1)).setDate(0));
var copt = {
fd : fd.getDay(),
lld : ldlm.getDate(),
ld : ld.getDate()
};
var offsetDayStart = ((copt.fd < opt.dayOffset) ? (opt.dayOffset - 7) : 1);
var offsetDayEnd = ((ld.getDay() < opt.dayOffset) ? (7 - ld.getDay()) : ld.getDay());
for (var d = offsetDayStart, dE = (copt.fd + copt.ld + (7 - offsetDayEnd)); d < dE; d++) $(target).append(((d <= (copt.fd - opt.dayOffset)) ? '<div id="' + opt.cID + 'd' + d + '" class="pday">' + (copt.lld - ((copt.fd - opt.dayOffset) - d)) + '</div>' : ((d > ((copt.fd - opt.dayOffset) + copt.ld)) ? '<div id="' + opt.cID + 'd' + d + '" class="aday">' + (d - ((copt.fd - opt.dayOffset) + copt.ld)) + '</div>' : '<div id="' + opt.cID + 'd_' + (fd.getMonth() + 1) + '_' + (d - (copt.fd - opt.dayOffset)) + '_' + fd.getFullYear() + '" class="' + ((opt.dCheck(new Date((new Date(fd.getTime())).setDate(d - (copt.fd - opt.dayOffset))))) ? 'day' : 'invday') + '">' + (d - (copt.fd - opt.dayOffset)) + '</div>')));
$(target).find('div[id^=' + opt.cID + 'd]:first, div[id^=' + opt.cID + 'd]:nth-child(7n+2)').before('<br style="clear:both; font-size:0.1em;" />');$(target).find('div[id^=' + opt.cID + 'd_]:not(.invday)').bind("mouseover mouseout click", $.extend({}, opt), function(e) {
if ($('.jCalMask', e.data._target).length > 0) return false;
var osDate = new Date($(this).attr('id').replace(/c[0-9]{1,}d_([0-9]{1,2})_([0-9]{1,2})_([0-9]{4})/, '$1/$2/$3'));
if (e.data.forceWeek) osDate.setDate(osDate.getDate() + (e.data.dayOffset - osDate.getDay()));
var sDate = new Date(osDate.getTime());
if (e.type == 'click') $('div[id*=d_]', e.data._target).stop().removeClass('selectedDay').removeClass('overDay').css('backgroundColor', '');
for (var di = 0, ds = $(e.data._target).data('days'); di < ds; di++) {
var currDay = $(e.data._target).find('#' + e.data.cID + 'd_' + (sDate.getMonth() + 1) + '_' + sDate.getDate() + '_' + sDate.getFullYear());
if (currDay.length == 0 || $(currDay).hasClass('invday')) break;
if (e.type == 'mouseover') $(currDay).addClass('overDay');
else if (e.type == 'mouseout') $(currDay).stop().removeClass('overDay').css('backgroundColor', '');
else if (e.type == 'click') $(currDay).stop().addClass('selectedDay');
sDate.setDate(sDate.getDate() + 1);
}
if (e.type == 'click') {
e.data.day = osDate;e.data.callback(osDate, di);
di = ds;$(e.data._target).data('day', e.data.day).data('days', di);
}
});
};})(jQuery);
And code in html:
<script language="JavaScript" type="text/javascript" src="${contextPath}include/js/jCal.min.js"></script>
<script language="javascript">
var calSettings = {
1:{calDay: 0, names: ['S','M','T','W','T','F','S']}, //sunday
2:{calDay: 1, names: ['M','T','W','T','F','S','S']}, //monday
3:{calDay: -5, names: ['T','W','T','F','S','S','M']}, //tuesday
4:{calDay: -4, names: ['W','T','F','S','S','M','T']}, //wednesday
5:{calDay: -3, names: ['T','F','S','S','M','T','W']}, //thursday
6:{calDay: -2, names: ['F','S','S','M','T','W','T']}, //friday
7:{calDay: -1, names: ['S','S','M','T','W','T','F']}}; //saturday
busyDays= new Array($busyDays);
calendarMaxDateTime = $calendarMaxDate.getTime();
jQuery(document).ready(function () {
$('#calOne').jCal({
day: new Date($calendarSetDate.getTime()),
days: 7,
showMonths: 5,
monthSelect: true,
forceWeek: true, // force full week selection
dow: calSettings[${defaultCheckinDay}].names,
callback: function (day, days) {
if(days==7){//disabling selection of periods shorter than 7 days
document.getElementById('bookingForm1')["filter_date"].value=day.getDate();
document.getElementById('bookingForm1')["filter_month"].value=day.getMonth();
document.getElementById('bookingForm1')["filter_year"].value=day.getFullYear();
document.getElementById('bookingForm1').submit();
return true;
}
}
});
});
</script>
I dont know where is problem, i looking in this script few hours i cant detect bug. Plz help.
I changes two line of code in this function in JavaScript and now works:
function drawCal(target, opt) {
for (var ds = 0, length = opt.dow.length; ds < length; ds++) $(target).append('<div class="dow">' + opt.dow[ds] + '</div>');
var fd = new Date(new Date(opt.day.getTime()).setDate(1));
var ldlm = new Date(new Date(fd.getTime()).setDate(0));
var ld = new Date(new Date(new Date(fd.getTime()).setMonth(fd.getMonth() + 1)).setDate(0));
var copt = {
fd : fd.getDay(),
lld : ldlm.getDate(),
ld : ld.getDate()
};
var offsetDayStart = ((copt.fd < opt.dayOffset) ? (opt.dayOffset - 7) : 1);
var offsetDayEnd = ((ld.getDay() < opt.dayOffset) ? (7 - ld.getDay()) : ld.getDay());
if(offsetDayEnd == 6) offsetDayEnd = 5;
for (var d = offsetDayStart, dE = (copt.fd + copt.ld + (7 - offsetDayEnd)); d < dE; d++) $(target).append(((d <= (copt.fd - opt.dayOffset)) ? '<div id="' + opt.cID + 'd' + d + '" class="pday">' + (copt.lld - ((copt.fd - opt.dayOffset) - d)) + '</div>' : ((d > ((copt.fd - opt.dayOffset) + copt.ld)) ? '<div id="' + opt.cID + 'd' + d + '" class="aday">' + (d - ((copt.fd - opt.dayOffset) + copt.ld)) + '</div>' : '<div id="' + opt.cID + 'd_' + (fd.getMonth() + 1) + '_' + (d - (copt.fd - opt.dayOffset)) + '_' + fd.getFullYear() + '" class="' + ((opt.dCheck(new Date((new Date(fd.getTime())).setDate(d - (copt.fd - opt.dayOffset))))) ? 'day' : 'invday') + '">' + (d - (copt.fd - opt.dayOffset)) + '</div>')));
$(target).find('div[id^=' + opt.cID + 'd]:first, div[id^=' + opt.cID + 'd]:nth-child(7n+2)').before('<br style="clear:both; font-size:0.1em;" />');$(target).find('div[id^=' + opt.cID + 'd_]:not(.invday)').bind("mouseover mouseout click", $.extend({}, opt), function(e) {
if ($('.jCalMask', e.data._target).length > 0) return false;
var osDate = new Date($(this).attr('id').replace(/c[0-9]{1,}d_([0-9]{1,2})_([0-9]{1,2})_([0-9]{4})/, '$1/$2/$3'));
osDate.setDate(osDate.getDate() + 1);
if (e.data.forceWeek) osDate.setDate(osDate.getDate() + (e.data.dayOffset - osDate.getDay()));
var sDate = new Date(osDate.getTime());
if (e.type == 'click') $('div[id*=d_]', e.data._target).stop().removeClass('selectedDay').removeClass('overDay').css('backgroundColor', '');
for (var di = 0, ds = $(e.data._target).data('days'); di < ds; di++) {
var currDay = $(e.data._target).find('#' + e.data.cID + 'd_' + (sDate.getMonth() + 1) + '_' + sDate.getDate() + '_' + sDate.getFullYear());
if (currDay.length == 0 || $(currDay).hasClass('invday')) break;
if (e.type == 'mouseover') $(currDay).addClass('overDay');
else if (e.type == 'mouseout') $(currDay).stop().removeClass('overDay').css('backgroundColor', '');
else if (e.type == 'click') $(currDay).stop().addClass('selectedDay');
sDate.setDate(sDate.getDate() + 1);
}
if (e.type == 'click') {
e.data.day = osDate;e.data.callback(osDate, di);
di = ds;$(e.data._target).data('day', e.data.day).data('days', di);
}
});
}

js - how to output values from function into HTML table

I've created a calculator to show repayments over the term of the loan.
I've managed to calculate each months payment, interest, remaining loan but I'm trying to output this into a table. The columns will be a fixed number (5) but the rows should dynamically update based on the number of months.
I've seen a few similar posts but can't get it to work for my code.
Code below and in jsfiddle
HTML
<div class="mortgageInput">
<form method="POST" name="calc" onclick="validateForm();repayment();return false;">
<label>Amount </label>
<input type="textbox" id="loan" value="100000"><br>
<label>Years</label>
<input type="textbox" id="years" value="15"><br>
<label>Rate (%)</label>
<input type="textbox" id="rate" value="6.00" onkeyup="calculate"><br>
<input type="button" value="Calculate" id="btn"><br>
<label>Monthly Repayment</label>
<input type="textbox" id="monthlyRepayment"><br>
<label>Monthly Interest Only</label>
<input type="textbox" id="interest"><br>
<label>Monthly Capital Repayment</label>
<input type="textbox" id="capitalRepayment"><br>
<label>Total Interest</label>
<input type="textbox" id="totalInterest">
</form>
</div>
<br>
Output into table...<p id="demo"></p>
JS
(document).on("keyup", calculate());
function validateForm(){
var validation = true;
validation &= calculate();
validation &= pmt();
return validation;
}
function calculate() {
var p = document.querySelector("#loan").value;
var y = document.querySelector("#years").value;
var rate = document.querySelector("#rate").value;
var r = rate / 100 / 12;
var n = y * 12;
var I = (p * r);
var monthlyPayment = -pmt(r,n,p);
var mr = (monthlyPayment - I);
var ti = (monthlyPayment) * n - p;
var list = JSON.stringify((computeSchedule(p, rate, 12, y, monthlyPayment)), 0, 4);
document.querySelector("#interest").value = I.toFixed(2);
document.querySelector("#totalInterest").value = ti.toFixed(2);
document.querySelector("#capitalRepayment").value = mr.toFixed(2);
document.querySelector("#monthlyRepayment").value = monthlyPayment.toFixed(2);
document.getElementById("demo").innerHTML = list;
}
function pmt(rate,nper,pv) {
var pvif, pmt;
pvif = Math.pow( 1 + rate, nper);
pmt = rate / (pvif - 1) * -(pv * pvif);
return pmt;
}
function computeSchedule(loan_amount, interest_rate, payments_per_year, years, payment) {
var schedule = [];
var remaining = loan_amount;
var number_of_payments = payments_per_year * years;
for (var i=0; i<=number_of_payments; i++) {
var interest = remaining * (interest_rate/100/payments_per_year);
var principle = (payment-interest);
var row = [i, payment, interest>0?interest:0, principle>0?principle:0, remaining>0?remaining:0];
schedule.push(row);
remaining -= principle
}
return schedule;
}
the above answer is right but if concern about performance do insert html outside loop
var list = computeSchedule(p, rate, 12, y, monthlyPayment);
var tables = "";
for (var i = 0; i < list.length; i++) {
tables += "<tr>" +
"<td>" + list[i][0] + "</td>" +
"<td>" + list[i][1] + "</td>" +
"<td>" + list[i][2] + "</td>" +
"<td>" + list[i][3] + "</td>" +
"<td>" + list[i][4] + "</td>" +
"</tr>";
}
document.getElementById("demo").innerHTML = '<table>' + tables + '</table>';
I am not sure if I understand you correctly, but this should normally be the solution. You're fiddle printed some js errors, I haven't fixed them in this example.
function validateForm(){
var validation = true;
validation &= calculate();
validation &= pmt();
return validation;
}
function calculate() {
var p = document.querySelector("#loan").value;
var y = document.querySelector("#years").value;
var rate = document.querySelector("#rate").value;
var r = rate / 100 / 12;
var n = y * 12;
var I = (p * r);
var monthlyPayment = -pmt(r,n,p);
var mr = (monthlyPayment - I);
var ti = (monthlyPayment) * n - p;
var list = JSON.stringify((computeSchedule(p, rate, 12, y, monthlyPayment)), 0, 4);
document.querySelector("#interest").value = I.toFixed(2);
document.querySelector("#totalInterest").value = ti.toFixed(2);
document.querySelector("#capitalRepayment").value = mr.toFixed(2);
document.querySelector("#monthlyRepayment").value = monthlyPayment.toFixed(2);
var list = computeSchedule(p, rate, 12, y, monthlyPayment);
console.log(list.length);
for (var i=0; i < list.length; i++) {
document.getElementById("test").innerHTML += "<tr><td>" + list[i][0] + "</td><td>" + list[i][1] + "</td><td>" + list[i][2] + "</td><td>" + list[i][3] + "</td><td>" + list[i][4] + "</td></tr>";
}
}
function pmt(rate,nper,pv) {
var pvif, pmt;
pvif = Math.pow( 1 + rate, nper);
pmt = rate / (pvif - 1) * -(pv * pvif);
return pmt;
}
function computeSchedule(loan_amount, interest_rate, payments_per_year, years, payment) {
var schedule = [];
var remaining = loan_amount;
var number_of_payments = payments_per_year * years;
for (var i=0; i<=number_of_payments; i++) {
var interest = remaining * (interest_rate/100/payments_per_year);
var principle = (payment-interest);
var row = [i, payment, interest>0?interest:0, principle>0?principle:0, remaining>0?remaining:0];
schedule.push(row);
remaining -= principle
}
return schedule;
}
table {
border-spacing: 0;
}
table td {
border: 1px solid #666;
padding: 0 3px;
}
<div class="mortgageInput">
<form method="POST" name="calc" onclick="validateForm();repayment();return false;">
<label>Amount </label>
<input type="textbox" id="loan" value="100000"><br>
<label>Years</label>
<input type="textbox" id="years" value="15"><br>
<label>Rate (%)</label>
<input type="textbox" id="rate" value="6.00" onkeyup="calculate"><br>
<input type="button" value="Calculate" id="btn"><br>
<label>Monthly Repayment</label>
<input type="textbox" id="monthlyRepayment"><br>
<label>Monthly Interest Only</label>
<input type="textbox" id="interest"><br>
<label>Monthly Capital Repayment</label>
<input type="textbox" id="capitalRepayment"><br>
<label>Total Interest</label>
<input type="textbox" id="totalInterest">
</form>
</div>
<br>
<table id="test">
</table>
The result of computeSchedule contains a two dimensional array. You should be able to loop through it with two nested for loops. Then you can compose your table.
Very simple example would look like this:
var demoList = computeSchedule(p, rate, 12, y, monthlyPayment);
var table = "<table>";
for (var rowIndex=0; rowIndex <= n; rowIndex++) {
var row = "<tr><td>#" + rowIndex + "</td>";
for(var colIndex = 0; colIndex < 4; colIndex++) {
row += "<td>" + demoList[rowIndex][colIndex] + "</td>";
}
table += row + "</tr>";
}
document.getElementById("output").innerHTML = table + "</table>";
You can also try the life version here: https://fiddle.jshell.net/aua4g8e7/

How can I detect if there is a piece in the moving piece's way?

I've been working on my first chess game and I got to a problem I can't solve, how can I detect if there's a piece in front of a moving piece's way?.
For example:
Let's say the player select a black rook on line 3 column 4 and then click on the slot on line 0 column 4
0 1 2 3 4
+----------+
0|_|_|_|_|__| 0,4
1|_|_|_|_|♙| 1,4
2|_|_|_|_|__| 2,4
3|_|_|_|_|♜| 3,4
4|_|_|_|_|__|
The problem is, on the black rook's way to 0,4 there's a white pawn. How can I detect that white pawn?
var piece = [{
"white": [
"&#9812", //king
"&#9813", //queen
"&#9814", //rook
"&#9815", //bishop
"&#9816", //knight
"&#9817" //pawn
]
}, {
"black": [
"&#9818", //king
"&#9819", //queen
"&#9820", //rook
"&#9821", //bishop
"&#9822", //knight
"&#9823" //pawn
]
}];
var slot = [];
var board = document.getElementById('main');
var selected = '';
for (var i = 0; i < 8; i++) {
slot.push(['']);
for (var j = 0; j < 8; j++) {
slot[i].push(['']);
}
}
slot[6][0] = piece[1].black[5];
slot[6][1] = piece[1].black[5];
slot[6][2] = piece[1].black[5];
slot[6][3] = piece[1].black[5];
slot[6][4] = piece[1].black[5];
slot[6][5] = piece[1].black[5];
slot[6][6] = piece[1].black[5];
slot[6][7] = piece[1].black[5];
slot[7][0] = piece[1].black[2];
slot[7][7] = piece[1].black[2];
slot[7][1] = piece[1].black[4];
slot[7][6] = piece[1].black[4];
slot[7][2] = piece[1].black[3];
slot[7][5] = piece[1].black[3];
slot[7][3] = piece[1].black[1];
slot[7][4] = piece[1].black[0];
slot[1][0] = piece[0].white[5];
slot[1][1] = piece[0].white[5];
slot[1][2] = piece[0].white[5];
slot[1][3] = piece[0].white[5];
slot[1][4] = piece[0].white[5];
slot[1][5] = piece[0].white[5];
slot[1][6] = piece[0].white[5];
slot[1][7] = piece[0].white[5];
slot[0][0] = piece[0].white[2];
slot[0][7] = piece[0].white[2];
slot[0][1] = piece[0].white[4];
slot[0][6] = piece[0].white[4];
slot[0][2] = piece[0].white[3];
slot[0][5] = piece[0].white[3];
slot[0][3] = piece[0].white[1];
slot[0][4] = piece[0].white[0];
for (var i = 0; i < 8; i++) {
for (var j = 0; j < 8; j++) {
if (i < 2) {
board.innerHTML += '<div class="slot" id="' + (i + '' + j) + '" style="width:30px;height:30px;top:' + (i * 30) + 'px;left:' + (j * 30) + 'px;"><div class="' + slot[i][j] + ' white" >' + slot[i][j] + '</div></div>';
}
if (i > 1 && i < 6) {
board.innerHTML += '<div class="slot" id="' + (i + '' + j) + '" style="width:30px;height:30px;top:' + (i * 30) + 'px;left:' + (j * 30) + 'px;"></div>';
}
if (i > 5 && i < 7) {
board.innerHTML += '<div class="slot" id="' + (i + '' + j) + '" style="width:30px;height:30px;top:' + (i * 30) + 'px;left:' + (j * 30) + 'px;"><div class="' + slot[i][j] + ' piece black pawn" >' + slot[i][j] + '</div></div>';
}
if ((i === 7 && j === 0) || (i === 7) && j === 7) {
board.innerHTML += '<div class="slot" id="' + (i + '' + j) + '" style="width:30px;height:30px;top:' + (i * 30) + 'px;left:' + (j * 30) + 'px;"><div class="' + slot[i][j] + ' piece black rook" >' + slot[i][j] + '</div></div>';
}
if ((i === 7 && j === 1) || (i === 7) && j === 6) {
board.innerHTML += '<div class="slot" id="' + (i + '' + j) + '" style="width:30px;height:30px;top:' + (i * 30) + 'px;left:' + (j * 30) + 'px;"><div class="' + slot[i][j] + ' piece black knight" >' + slot[i][j] + '</div></div>';
}
if ((i === 7 && j === 2) || (i === 7) && j === 5) {
board.innerHTML += '<div class="slot" id="' + (i + '' + j) + '" style="width:30px;height:30px;top:' + (i * 30) + 'px;left:' + (j * 30) + 'px;"><div class="' + slot[i][j] + ' piece black bishop" >' + slot[i][j] + '</div></div>';
}
if ((i === 7 && j === 3)) {
board.innerHTML += '<div class="slot" id="' + (i + '' + j) + '" style="width:30px;height:30px;top:' + (i * 30) + 'px;left:' + (j * 30) + 'px;"><div class="' + slot[i][j] + ' piece black queen" >' + slot[i][j] + '</div></div>';
}
if ((i === 7 && j === 4)) {
board.innerHTML += '<div class="slot" id="' + (i + '' + j) + '" style="width:30px;height:30px;top:' + (i * 30) + 'px;left:' + (j * 30) + 'px;"><div class="' + slot[i][j] + ' piece black king" >' + slot[i][j] + '</div></div>';
}
}
}
$(document).mousedown(function(e) {
e.preventDefault();
});
//Select Piece
$('.slot > .piece').mousedown(function() {
$('.slot > .piece').css({
'background-color': '#fff'
});
$(this).css({
'background-color': '#afa'
});
selected = this;
});
//Drop Piece
$('.slot').mousedown(function() {
var id = [];
try {
id.push(
parseInt($(selected).parent().attr('id').substring(0, 1), 10),
parseInt($(selected).parent().attr('id').substring(1, 2), 10),
parseInt($(this).attr('id').substring(0, 1), 10),
parseInt($(this).attr('id').substring(1, 2), 10)
);
} catch (e) {
console.info('Select one of your pieces!');
}
//Pawn Moves
if (selected !== '' && !$(this).children().hasClass('piece') && id[0] == (id[2] + 1) && id[1] == id[3] && $(selected).hasClass('pawn') && !$(this).children().hasClass('white')) {
$(this).empty();
$(this).append(selected);
selected = '';
}
if (selected !== '' && !$(this).children().hasClass('piece') && id[0] == (id[2] + 1) && id[1] !== id[3] && $(selected).hasClass('pawn') && $(this).children().hasClass('white')) {
$(this).empty();
$(this).append(selected);
selected = '';
}
if (selected !== '' && !$(this).children().hasClass('piece') && (id[0] == id[2] || id[1] == id[3]) && $(selected).hasClass('rook')) {
$(this).empty();
$(this).append(selected);
selected = '';
}
if (selected !== '' && !$(this).children().hasClass('piece') && $(selected).hasClass('knight') && ((id[0] == id[2] - 2 && id[1] == id[3] - 1) || (id[0] == id[2] - 1 && id[1] == id[3] - 2) || (id[0] == id[2] - 2 && id[1] == id[3] + 1) || (id[0] == id[2] - 1 && id[1] == id[3] + 2) || (id[0] == id[2] + 1 && id[1] == id[3] - 2) || (id[0] == id[2] + 2 && id[1] == id[3] - 1) || (id[0] == id[2] + 1 && id[1] == id[3] + 2) || (id[0] == id[2] + 2 && id[1] == id[3] + 1))) {
$(this).empty();
$(this).append(selected);
selected = '';
}
if (selected !== '' && !$(this).children().hasClass('piece') && $(selected).hasClass('bishop') && (Math.abs(id[0] - id[2]) === Math.abs(id[1] - id[3]))) {
$(this).empty();
$(this).append(selected);
selected = '';
}
if (selected !== '' && !$(this).children().hasClass('piece') && $(selected).hasClass('queen') && (Math.abs(id[0] - id[2]) === Math.abs(id[1] - id[3]) || (id[0] == id[2] || id[1] == id[3]))) {
$(this).empty();
$(this).append(selected);
selected = '';
}
if (selected !== '' && !$(this).children().hasClass('piece') && $(selected).hasClass('king') && ((Math.abs(id[0] - id[2]) === 1) || (Math.abs(id[1] - id[3]) === 1) || ((id[0] + 1) == id[2] || (id[1] + 1) == id[3]))) {
$(this).empty();
$(this).append(selected);
selected = '';
}
});
/*
00 01 02 03 04 05 06 07
10 11 12 13 14 15 16 17
20 21 22 23 24 25 26 27
30 31 32 33 34 35 36 37
40 41 42 43 44 45 46 47
50 51 52 53 54 55 56 57
60 61 62 63 64 65 66 67
70 71 72 73 74 75 76 77
*/
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Roboto+Condensed' rel='stylesheet' type='text/css'>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=1" />
<title>Chessisjustlikecheese</title>
<style>
html,
body {
position: absolute;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
#main {
position: absolute;
width: 240px;
height: 240px;
top: calc(50% - 120px);
left: calc(50% - 120px);
}
.slot {
z-index: 10;
position: absolute;
outline: 1px solid #000;
text-align: center;
background-color: #fff;
cursor: crosshair;
}
.black,
.white {
width: 100%;
height: 100%;
zoom: 1.7;
line-height: 20px;
}
</style>
</head>
<body>
<div id="main">
</div>
</body>
</html>

Categories