Number Page Navigation showing Last 500 Posts Instead of 10000 posts - javascript

Thanks in Advance to helping my problem.
I have 10,000 Pages in my Blogger Site and using following HTML code to show Number page navigation on main page
Here my issue is, there are morethan 10,000 posts but it uses first 500 posts and showing 18 pages (it should be more than 300+ pages)
I changes 28 posts / page and as it showing 18 x 28 pages = 500 or less
When i have 10,000 posts it should show 28 posts x 350+ pages
You can have a Look on : Dealdimer.com
Please someone guide me where the issue is, Sorry if i'm poor in explaining my concern.
My Code as:
<style type="text/CSS">
.showpageArea a {
text-decoration:underline;
}
.showpageNum a {
text-decoration:none;
border: 1px solid #7AA1C3;
margin:0 3px;
padding:3px;
}
.showpageNum a:hover {
border: 1px solid #7AA1C3;
background-color:#F6F6F6;
}
.showpagePoint {
color:#333;
text-decoration:none;
border: 1px solid #7AA1C3;
background: #F6F6F6;
margin:0 3px;
padding:3px;
}
.showpageOf {
text-decoration:none;
padding:3px;
margin: 0 3px 0 0;
}
.showpage a {
text-decoration:none;
border: 1px solid #7AA1C3;
padding:3px;
}
.showpage a:hover {
text-decoration:none;
}
.showpageNum a:link,.showpage a:link {
text-decoration:none;
color:#7AA1C3;
}
</style>
<script type="text/JavaScript">
function showpageCount(json) {
var thisUrl = location.href;
var htmlMap = new Array();
var isFirstPage = thisUrl.substring(thisUrl.length-5,thisUrl.length)==".com/";
var isLablePage = thisUrl.indexOf("/search/label/")!=-1;
var isPage = thisUrl.indexOf("/search?updated")!=-1;
var thisLable = isLablePage ? thisUrl.substr(thisUrl.indexOf("/search/label/")+14,thisUrl.length) : "";
thisLable = thisLable.indexOf("?")!=-1 ? thisLable.substr(0,thisLable.indexOf("?")) : thisLable;
var thisNum = 1;
var postNum=1;
var itemCount = 0;
var fFlag = 0;
var eFlag = 0;
var html= '';
var upPageHtml ='';
var downPageHtml ='';
var pageCount = 28;
var displayPageNum = 5;
var upPageWord = 'Previous';
var downPageWord = 'Next';
var labelHtml = '<span class="showpageNum"><a href="/search/label/'+thisLable+'?&max-results='+pageCount+'">';
for(var i=0, post; post = json.feed.entry[i]; i++) {
var timestamp = post.published.$t.substr(0,10);
var title = post.title.$t;
if(isLablePage){
if(title!=''){
if(post.category){
for(var c=0, post_category; post_category = post.category[c]; c++) {
if(encodeURIComponent(post_category.term)==thisLable){
if(itemCount==0 || (itemCount % pageCount ==(pageCount-1))){
if(thisUrl.indexOf(timestamp)!=-1 ){
thisNum = postNum;
}
postNum++;
htmlMap[htmlMap.length] = '/search/label/'+thisLable+'?updated-max='+timestamp+'T00%3A00%3A00%2B08%3A00&max-results='+pageCount;
}
}
}
}//end if(post.category){
itemCount++;
}
}else{
if(title!=''){
if(itemCount==0 || (itemCount % pageCount ==(pageCount-1))){
if(thisUrl.indexOf(timestamp)!=-1 ){
thisNum = postNum;
}
if(title!='') postNum++;
htmlMap[htmlMap.length] = '/search?updated-max='+timestamp+'T00%3A00%3A00%2B08%3A00&max-results='+pageCount;
}
}
itemCount++;
}
}
for(var p =0;p< htmlMap.length;p++){
if(p>=(thisNum-displayPageNum-1) && p<(thisNum+displayPageNum)){
if(fFlag ==0 && p == thisNum-2){
if(thisNum==2){
if(isLablePage){
upPageHtml = labelHtml + upPageWord +'</a></span>';
}else{
upPageHtml = '<span class="showpage">'+ upPageWord +'</span>';
}
}else{
upPageHtml = '<span class="showpage">'+ upPageWord +'</span>';
}
fFlag++;
}
if(p==(thisNum-1)){
html += '<span class="showpagePoint">'+thisNum+'</span>';
}else{
if(p==0){
if(isLablePage){
html = labelHtml+'1</a></span>';
}else{
html += '<span class="showpageNum">1</span>';
}
}else{
html += '<span class="showpageNum">'+ (p+1) +'</span>';
}
}
if(eFlag ==0 && p == thisNum){
downPageHtml = '<span class="showpage"> '+ downPageWord +'</span>';
eFlag++;
}
}//end if(p>=(thisNum-displayPageNum-1) && p<(thisNum+displayPageNum)){
}//end for(var p =0;p< htmlMap.length;p++){
if(thisNum>1){
if(!isLablePage){
html = ''+upPageHtml+' '+html +' ';
}else{
html = ''+upPageHtml+' '+html +' ';
}
}
html = '<div class="showpageArea"><span style="COLOR: #000;" class="showpageOf"> Pages ('+(postNum-1)+')</span>'+html;
if(thisNum<(postNum-1)){
html += downPageHtml;
}
if(postNum==1) postNum++;
html += '</div>';
if(isPage || isFirstPage || isLablePage){
var pageArea = document.getElementsByName("pageArea");
var blogPager = document.getElementById("blog-pager");
if(postNum <= 2){
html ='';
}
for(var p =0;p< pageArea.length;p++){
pageArea[p].innerHTML = html;
}
if(pageArea&&pageArea.length>0){
html ='';
}
if(blogPager){
blogPager.innerHTML = html;
}
}
}
</script>
<script src="/feeds/posts/summary?alt=json-in-script&callback=showpageCount&max-results=99999" ; type="text/javascript"></script>

Related

Generate different text in every tile javascript

I have arrays of strings with names and surnames. I created username which consist of random name and random surname and I want to display different username in every generated tile. I tried to splite names and surnames and than add it do array and get random array index but it didn't work. Better solution would be to use my "username". Biggest problem is that I can't modify my getData() function - it always assign the same username to each tile.
function createGrid(x, y) {
for (var cols = 0; cols < x; cols++) {
for (var rows = 0; rows < y; rows++) {
console.log(namesArr)
console.log(x*y)
numberOfTiles = x*y;
var randonIndex = Math.floor(Math.random() * numberOfTiles);
// $(".usernameSpace").html(namesArr[randomIndex]);
//Doesn't work here
$('#container').append("<div class='grid'><div class = 'usernameSpace'></div></div>");
};
};
$('.grid').width(800 / x);
$('.grid').height(800 / x);
};
function refreshGrid() {
var x = $("#colsNumber")[0].value;
var y = $("#rowsNumber")[0].value;
$('.grid').remove();
createGrid(x, y);
};
function getData(count) {
var names = ["Michal ", "Jan ", "Katarzyna ", "Andrzej ", "Jozef ", "Bartek ", "Mikolaj ", "Tomasz ", "Julian ", "Brajan ", "Dzesika "];
var surnames = ["Noga ", "Kowalski ", "Nowak ", "Pazura ", "Duda ", "Komorowski ", "Tomczyk ", "Jozefowicz ", "Lechicki ", "Goldberg "];
result = [];
for (var i = 0; i < count; i++) {
var randomNameIndex = Math.floor(Math.random() * names.length);
var randomSurnameIndex = Math.floor(Math.random() * surnames.length);
var name = names[randomNameIndex];
var surname = surnames[randomSurnameIndex];
result.push({
name: name,
surname: surname
});
}
return result
}
function textDisplay() {
var numberOfTiles = 12;
//for (i = 0; i <= numberOfTiles; i++) {
var data = getData(12);
//var username = "";
////////////////////////////////////////////////////////////////////
username = "";
$.each(data, function (i, { name, surname }) {
username += ` ${name} ${surname}`;
});
////////////////////////////////////////////////////////////////////
// }
namesToDisplay = "";
surnamesToDisplay = "";
$.each(data, function (i, { name }) {
namesToDisplay += `${name}`;
});
$.each(data, function (i, { surname }) {
surnamesToDisplay += `${surname}`;
});
console.log(username)
console.log(namesToDisplay)
console.log(surnamesToDisplay)
//$(".usernameSpace").html(username);
namesArr = namesToDisplay.split(" ");
console.log(namesArr)
$(".usernameSpace").html(namesArr[2]);
}
function AssignUsername(Class, content) {
var container = document.getElementsByClassName(Class);
$(container).html(content);
}
$(document).ready(function () {
$(".startBtn").click(function () {
refreshGrid();
textDisplay();
});
});
#container {
position: relative;
margin:auto;
height:800px;
width:800px;
}
.grid{
outline:5px solid white;
margin:0;
padding:0;
border:none;
background-color: #212121;
display:inline-block;
color: white;
}
.input{
width: 15%;
background-color: #757575;
font-size: 18px;
border: 3px;
height: 4%;
border-radius: 5px;
color: white;
}
html {
font-family: 'Arial';
}
.startBtn{
background-color: #4b4b4b;
border-radius: 10px;
color: white;
}
#textDisplay{
height:800px;
width:800px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<head>
<link rel=stylesheet type="text/css" href="MetroUI 03'2018 basic.css">
<script src="jquery.js"></script>
<script src="MetroUI 03'2018 basic.js"></script>
</head>
<body onload="textDisplay()">
<p>
Give me width of grid:
</p>
<div>
<input class='input' id='colsNumber' type='number'>
</div>
<p>
Give me height of grid:
</p>
<div>
<input class='input' id='rowsNumber' type='number'>
</div>
<button class="startBtn">START!</button>
<div class='nameDisplay'></div>
<div class="Container"></div>
<div id = "container"></div>
</body>
</html>
In your code when you do:
$(".usernameSpace").html(namesArr[2]);
You are assigning all titles with that class to the same HTML values. Instead iterate through your titles and assign it a value based on your data variable:
$(".usernameSpace").each(function(idx){
$(this).html(data[idx].surname);
});
Although I'd recommend storing the names directly in the data attribute of the .usernameSpace elements as you create them. Then you could just use $(this).data("surname") when you iterate through your elements. That way will be more safer as well in the event that data and the number of .usernameSpace elements differs, along with that it will make the code simpler.
Here is a fiddle example of what I described above
function createGrid(x, y) {
for (var cols = 0; cols < x; cols++) {
for (var rows = 0; rows < y; rows++) {
console.log(namesArr)
console.log(x*y)
numberOfTiles = x*y;
var randonIndex = Math.floor(Math.random() * numberOfTiles);
// $(".usernameSpace").html(namesArr[randomIndex]);
//Doesn't work here
$('#container').append("<div class='grid'><div class = 'usernameSpace'></div></div>");
};
};
$('.grid').width(800 / x);
$('.grid').height(800 / x);
};
function refreshGrid() {
var x = $("#colsNumber")[0].value;
var y = $("#rowsNumber")[0].value;
$('.grid').remove();
createGrid(x, y);
};
function getData(count) {
var names = ["Michal ", "Jan ", "Katarzyna ", "Andrzej ", "Jozef ", "Bartek ", "Mikolaj ", "Tomasz ", "Julian ", "Brajan ", "Dzesika "];
var surnames = ["Noga ", "Kowalski ", "Nowak ", "Pazura ", "Duda ", "Komorowski ", "Tomczyk ", "Jozefowicz ", "Lechicki ", "Goldberg "];
result = [];
for (var i = 0; i < count; i++) {
var randomNameIndex = Math.floor(Math.random() * names.length);
var randomSurnameIndex = Math.floor(Math.random() * surnames.length);
var name = names[randomNameIndex];
var surname = surnames[randomSurnameIndex];
result.push({
name: name,
surname: surname
});
}
return result
}
function textDisplay() {
var numberOfTiles = 12;
//for (i = 0; i <= numberOfTiles; i++) {
var data = getData(12);
//var username = "";
////////////////////////////////////////////////////////////////////
username = [];
$.each(data, function (i, { name, surname }) {
username.push(` ${name} ${surname}`);
});
////////////////////////////////////////////////////////////////////
// }
namesToDisplay = "";
surnamesToDisplay = "";
$.each(data, function (i, { name }) {
namesToDisplay += `${name}`;
});
$.each(data, function (i, { surname }) {
surnamesToDisplay += `${surname}`;
});
console.log(username)
console.log(namesToDisplay)
console.log(surnamesToDisplay)
//$(".usernameSpace").html(username);
namesArr = namesToDisplay.split(" ");
console.log(namesArr)
$(".usernameSpace").each(function(idx){
$(this).html(username[idx]);
})
}
function AssignUsername(Class, content) {
var container = document.getElementsByClassName(Class);
$(container).html(content);
}
$(document).ready(function () {
$(".startBtn").click(function () {
refreshGrid();
textDisplay();
});
});
#container {
position: relative;
margin:auto;
height:800px;
width:800px;
}
.grid{
outline:5px solid white;
margin:0;
padding:0;
border:none;
background-color: #212121;
display:inline-block;
color: white;
}
.input{
width: 15%;
background-color: #757575;
font-size: 18px;
border: 3px;
height: 4%;
border-radius: 5px;
color: white;
}
html {
font-family: 'Arial';
}
.startBtn{
background-color: #4b4b4b;
border-radius: 10px;
color: white;
}
#textDisplay{
height:800px;
width:800px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<head>
<link rel=stylesheet type="text/css" href="MetroUI 03'2018 basic.css">
<script src="jquery.js"></script>
<script src="MetroUI 03'2018 basic.js"></script>
</head>
<body onload="textDisplay()">
<p>
Give me width of grid:
</p>
<div>
<input class='input' id='colsNumber' type='number'>
</div>
<p>
Give me height of grid:
</p>
<div>
<input class='input' id='rowsNumber' type='number'>
</div>
<button class="startBtn">START!</button>
<div class='nameDisplay'></div>
<div class="Container"></div>
<div id = "container"></div>
</body>
</html>

Moving an image from one <td> to another <td> on the same table

So I'm doing this school project. And I'm stuck with the main logic. I'm doing a Checkers game. I got all checker board and checker pieces, the problem is its movement.
Basically, I just want it so that when I click the image from one //td// and click to another //td//, the image moves or transfers to the new //td//. I used ID attributes for //td// as a friend suggested maybe I could start from there.
Thanks so much :)
<html>
<head>
<style>
body { background-color: #D1CDDF; }
p { font-family: Verdana, Geneva, sans-serif;
font-size: 30; }
img { width: 35px;
height: 35px; }
label { font-family: "Lucida Console", Monaco, monospace;
font-size: 15; }
.focused{ border: 2px solid yellow; }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
function saveScore() {
// syntax: $.post(URL,data,callback);
$.post("scores.php",
{
TheFile: $("#filename").val(),
TheMessage: $("#winner").val() + "\r\n"
}
,function(dataFromtheServer) {
$("#result").html(dataFromtheServer);
});
}
function openBoard()
{
$(document).ready(function()
{
var p1Name = document.getElementById("p1name").value;
var p2Name = document.getElementById("p2name").value;
var heading = "<center><p><font color=\"#cc33ff\">" + p1Name + " vs " + p2Name + "</font></p></center>";
var table = $('<table width=500px cellspacing=0px cellpadding=0px border=1px ></table>');
var rc;
var picName;
var picName2;
for( y = 1; y <= 8; y++ )
{
var row = $('<tr></tr>');
for ( var x = 1; x <= 8; x++)
{
rc = y + x;
// creating the images
picName = "p" + 1 + ".png" ;
var pic1 = $('<img>').attr('src',picName);
picName2 = "p" + 2 + ".png";
var pic2 = $('<img>').attr('src',picName2);
if(rc % 2 === 0)
{
if(y === 1 || y === 2 || y === 3)
{
var col1 = $('<td align=center height=50px width=50px bgcolor=#4E9660 ></td>').attr('id',y + '-' + x);
col1.html(pic1);
row.append(col1);
}
else if(y === 6 || y === 7 || y === 8)
{
var col2 = $('<td align=center height=50px width=50px bgcolor=#4E9660 ></td>').attr('id',y + '-' + x);
col2.html(pic2);
row.append(col2);
}
else
{
var col3 = $('<td align=center height=50px width=50px bgcolor=#4E9660 ></td>').attr('id',y + '-' + x);
row.append(col3);
}
}
else
{
var col4 = $('<td align=center height=50px width=50px bgcolor=#C4C160 ></td>').attr('id',y + '-' + x);
row.append(col4);
}
}
table.append(row);
}
document.getElementById("bBoard").style.visibility = "hidden";
$('#board').append(heading);
$('#board').append(table);
$(function()
{
$('img').click(function()
{
$('img').removeClass('focused');
$(this).addClass('focused');
$(this).setPosition()
});
});
});
}
</script>
</head>
<body>
<center>
<p>~Checkers~</p>
<table border=1 cellpadding=25px>
<tr><td><label>Player 1: <input type=text id=p1name /></label><br/><br/>
<label>Player 2: <input type=text id=p2name /></label><br/><br/>
<button id="bBoard" onclick="openBoard();">Start Game</button><br/><br/></td>
<td><div class="b" id="board"></div></td>
<td>
<input type=hidden id=filename value="players.txt" />
<label>Register Winner: <input type=text id=winner /></label><br/><br/>
<button id="bReg" onclick="saveScore();">Submit</button><br/><br/>
<div id="result"></div>
</td>
</td></tr>
</table>
</center>
</body>
All you need to do is get a DOM reference to the img element in quesiton and then call .appendChild(thatImgElement) on the td that it should be moved to.
Here's a simple example:
// Get reference to image to be moved
var img = document.getElementById("checkmark");
img.addEventListener("click", function(){
// Get reference to target container
var rightCell = document.getElementById("right");
// Move image into target
rightCell.appendChild(this);
});
table { width:300px; height:50px; }
table,td { border: 1px solid black; }
td { width: 50%; }
img { width:30px; }
<table>
<tr>
<td id="left"><img id="checkmark" src="https://i.stack.imgur.com/hyKmt.jpg"></td>
<td id="right"></td>
</tr>
</table>

Filter element if checkboxes are check or not JavaScript

I got a problem with my code. I coded a search bar which filter checkboxes by their name and I coded a function which only display the checkboxes selected. But there is a conflict.
Everytime I click on "Selected" everything is passing to a display : none;
So I tried to wrap my search bar into some div but it's not working as I imagined. I know that .parent() is the problem because it impacts the parent of my search bar, but I need it to hide the elements not selected so I don't succeed in solving it.
Here is the snippet to understand what I mean. Update it in your answer to let me see what was wrong.
Hope you guys will be able to help me.
function All() {
$("input").parent().show();
}
function OnlySelecteds() {
$("input:not(:checked)").parent().hide();
}
//array of options
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "June";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";
var target = new Array()
target[0] = "9";
target[1] = "8";
target[2] = "11";
var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";
var j = "";
var t = document.getElementById('t');
// the loop is creating the checkboxes with name, value...
for (var i in choices) {
//Name of checkboxes are their number so I convert the i into a string.
j = i.toString();
val = j;
//cap will be the value/text of choices[i]
var cb = document.createElement('input');
var label = document.createElement("label");
cap = choices[i];
var text = document.createTextNode(cap);
cb.type = 'checkbox';
cbh.appendChild(cb);
cb.name = cap;
cb.value = val;
label.appendChild(cb);
label.appendChild(text);
cbh.appendChild(label);
cb.addEventListener('click', updateText)
if (target.indexOf(i) >= 0) {
cb.checked = true;
}
}
updateText();
function updateText() {
t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
}
function updateCheckboxes(x) {
if ($('#SearchBar').val() == '') {
$('#checkboxes > label').show();
} else {
$('#checkboxes > label').hide();
$('#checkboxes > label:contains(' + $('#SearchBar').val() + ')').show();
}
}
* {
box-sizing: border-box;
}
#data {
padding: 5px;
width: 100vw;
}
.multiselect {
overflow: visible;
padding: 0;
padding-left: 1px;
border: none;
width: 100vw;
white-space: normal;
height: 75px;
}
.checkboxes {
height: 100px;
width: 100px;
border: 1px solid #000;
background-color: white;
margin-left: -1px;
display: inline-block;
}
label {
display: inline-block;
border: 1px grey solid;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<span onclick="All()">All</span> | <span onclick="OnlySelecteds()">Selected</span> | <input id="SearchBar" placeholder="Search for options.." type="text" oninput="updateCheckboxes(this)" autocomplete="off">
<form>
<div id="data">
<div class="multiselect">
<div id="c_b">
<div id="checkboxes">
</div>
</div>
</div>
</div>
</form>
<textarea id="t" style="display: none;"></textarea>
rather than only hide all your unchecked input, I would prefer to show all input first. that way, even after I searched something, then if I click "selected", it would still show all the selected input
function OnlySelecteds() {
$("input").parent().show();
$("input:not(:checked)").parent('label').hide();
}
demo : https://jsfiddle.net/Lzw1xg2n/1/
Change the function OnlySelecteds() to this:
function OnlySelecteds() {
$("input").closest('label').show();
$("input:not(:checked)").closest('label').hide();
}
function All() {
$("input").parent().show();
}
function OnlySelecteds() {
$("input").closest('label').show();
$("input:not(:checked)").closest('label').hide();
}
//array of options
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "June";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";
var target = new Array()
target[0] = "9";
target[1] = "8";
target[2] = "11";
var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";
var j = "";
var t = document.getElementById('t');
// the loop is creating the checkboxes with name, value...
for (var i in choices) {
//Name of checkboxes are their number so I convert the i into a string.
j = i.toString();
val = j;
//cap will be the value/text of choices[i]
var cb = document.createElement('input');
var label = document.createElement("label");
cap = choices[i];
var text = document.createTextNode(cap);
cb.type = 'checkbox';
cbh.appendChild(cb);
cb.name = cap;
cb.value = val;
label.appendChild(cb);
label.appendChild(text);
cbh.appendChild(label);
cb.addEventListener('click', updateText)
if (target.indexOf(i) >= 0) {
cb.checked = true;
}
}
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
updateText();
function updateText() {
t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
}
function updateCheckboxes(x) {
if ($('#SearchBar').val() == '') {
$('#checkboxes > label').show();
} else {
$('#checkboxes > label').hide();
$('#checkboxes > label:contains(' + $('#SearchBar').val() + ')').show();
}
}
* {
box-sizing: border-box;
}
#data {
padding: 5px;
width: 100vw;
}
.multiselect {
overflow: visible;
padding: 0;
padding-left: 1px;
border: none;
width: 100vw;
white-space: normal;
height: 75px;
}
.checkboxes {
height: 100px;
width: 100px;
border: 1px solid #000;
background-color: white;
margin-left: -1px;
display: inline-block;
}
label {
display: inline-block;
border: 1px grey solid;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<span onclick="All()">All</span> | <span onclick="OnlySelecteds()">Selected</span> | <input id="SearchBar" placeholder="Search for options.." type="text" oninput="updateCheckboxes(this)" autocomplete="off">
<form>
<div id="data">
<div class="multiselect">
<div id="c_b">
<div id="checkboxes">
</div>
</div>
</div>
</div>
</form>
<textarea id="t" style="display: none;"></textarea>

Javascript calculate function not calculating

I have recently been working on a project that has resulted in countless hours of frustration. The task is to create a Webpage that calculates a user's total cost depending on the different radio buttons / check boxes they select.
So, assuming all my other functions and constants are correct, is there anything wrong with my function or the calling of my function.
HTML
<input type = "button" value = "Submit" onclick="calculate();">
<table>
<tr><td>Workshop Total:</td> <td><div id="divWorkshopTotal"></div></td></tr>
<tr><td>Lodging Total:</td> <td><div id="divLodgingTotal"></div></td></tr>
<tr><td>Discount Amount:</td> <td><div id="divDiscount"></div></td></tr>
<tr><td>Sales Tax Amount:</td> <td><div id="divSalesTaxAmount"></div></td></tr>
<tr><td>Total Due:</td> <td><div id="divTotal"></div></td></tr>
</table>
JavaScript
function $(elementName){
return document.getElementById(elementName);
}
function calculate(){
clearOutput();
if (checkWorkshopSelected() > 3){
$("divWorkshopError").innerHTML = "* Selected workshops exceeds maximum of " + MAXIMUM_WORKSHOPS_SELECTED;
return;
} else if (checkWorkshopSelected() == 0){
$("divWorkshopError").innerHTML = "* No workshop(s) selected";
return;
}
var workshopCost = calculateWorkshopTotalCost();
var lodgingCost = calculateLodgingCost();
var subtotal = workshopCost + lodgingCost;
var discountRate = calculateDiscountRate();
var discountAmount = subtotal * discountRate;
if ($("chkTaxExempt").checked == false){
var salesTaxAmount = (subtotal - discountAmount) * SALES_TAX_RATE;
}
var totalCost = subtotal - discountAmount + salesTaxAmount;
$("divWorkshopTotal").innerHTML = workshopCost;
$("divLodgingTotal").innerHTML = lodgingCost;
$("divDiscount").innerHTML = discountAmount;
$("divSalesTaxAmount").innerHTML = salesTaxAmount;
$("divTotal").innerHTML = totalCost;
}
Please check out the code and only ask small doubts in comments. Otherwise please make a new question.
var SALES_TAX_RATE = 0.1,
MAXIMUM_WORKSHOPS_SELECTED = 3;
var data = {
productA: 10,
productB: 20,
productC: 25,
};
var prod = document.getElementsByClassName('prod'),
tax = $("tax"),
workshopTotal = $("workshopTotal"),
lodgingTotal = $("lodgingTotal"),
discount = $("discount"),
salesTaxAmount = $("salesTaxAmount"),
total = $("total"),
workshopError = $("workshopError"),
out = document.getElementsByClassName('out');
$("inputButton").addEventListener("click", calculate);
clearOutput();
function $(elementName){
return document.getElementById(elementName);
}
function calculate () {
clearOutput();
if (checkWorkshopSelected() >= MAXIMUM_WORKSHOPS_SELECTED) {
workshopError.innerHTML = "* Selected workshops exceeds maximum of " + MAXIMUM_WORKSHOPS_SELECTED;
return;
} else if (checkWorkshopSelected() == 0) {
workshopError.innerHTML = "* No workshop(s) selected";
return;
}
var workshopCost = calculateWorkshopTotalCost();
var lodgingCost = calculateLodgingCost();
var subtotal = workshopCost + lodgingCost;
var discountRate = calculateDiscountRate();
var discountAmount = subtotal * discountRate;
var salesTax = 0;
if (tax.checked == false){
salesTax = (subtotal - discountAmount) * SALES_TAX_RATE;
}
var totalCost = subtotal - discountAmount + salesTax;
outputPrice(workshopTotal, workshopCost);
outputPrice(lodgingTotal, lodgingCost);
outputPrice(discount, discountAmount);
outputPrice(salesTaxAmount, salesTax);
outputPrice(total, totalCost);
}
function clearOutput () {
for (var i=0; i<out.length; i++) {
var o = out[i];
o.innerHTML = "0,00"
}
workshopError.innerHTML = "";
}
function checkWorkshopSelected () {
var s = 0;
for (var i=0; i<prod.length; i++) {
var p = prod[i];
if (p.checked) s += 1;
}
return s;
}
function calculateLodgingCost () {
return 5;
}
function calculateWorkshopTotalCost () {
var t = 0;
for (var i=0; i<prod.length; i++) {
var p = prod[i];
if (p.checked) t += data[p.id];
}
return t;
}
function calculateDiscountRate () {
return 0.05;
}
function outputPrice (e, p) {
e.innerHTML = p.toFixed(2);
}
p {
line-height: 14px;
width: 200px;
}
#inputButton {
height: 32px;
margin-bottom: 10px;
}
#workshopError {
color: red;
float: right;
margin-bottom: 20px;
}
.prod + label {
font-weight: bold;
}
.out {
display: inline-block;
padding: 4px 12px;
margin: -6px 0;
background: #fff;
border: 1px solid #999;
border-radius: 3px;
font-family: monospace;
float: right;
}
.out:before {
content: "$";
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p><input type="checkbox" id="productA" class="prod"><label>Workshop A - 10</label></p>
<p><input type="checkbox" id="productB" class="prod"><label>Workshop B - 20</label></p>
<p><input type="checkbox" id="productC" class="prod"><label>Workshop C - 25</label></p>
<p><input type="checkbox" id="tax"><label>Tax 10%</label></p>
<p><input id="inputButton" type="button" value="Submit"><label id="workshopError"></label></p>
<p><label>Workshop Total:</label><span class="out" id="workshopTotal"></span></p>
<p><label>Lodging Total:</label><span class="out" id="lodgingTotal"></span></p>
<p><label>Discount Amount:</label><span class="out" id="discount"></span></p>
<p><label>Sales Tax Amount:</label><span class="out" id="salesTaxAmount"></span></p>
<p><label>Total Due:</label><span class="out" id="total"></span></p>
</body>
</html>

How to manipulate html <table> tags in between javascript function?

For example:
problem:
Make a corresponding table cell red colored.
I know I must use the .tag className in the style
but I don't know how to make the color changed for
html tags in javascript that sits in another function.
<style>
.tag { background-color : red ; }
</style>
<script>
var str = ["B","I","N","G","O"];
function table()
{
t+= "<tr>";
for(b=0;b<5;b++)
{
t+="<td>"+ document.getElementById("table").innerHTML + str[b] + "</td>";
}
t+="</tr>";
}
function changeColor()
{
var letter= document.getElementById("matching").value;
for(i=0;i<5;i++)
{
if(letter == str[i])
{
/*
here.
*/
}
}
}
</script>
Try something like this:
var str = ["B", "I", "N", "G", "O"];
function table() {
t += "<tr>";
for (b = 0; b < 5; b++) {
t += "<td" + (changeColor() ? " class='tag'" : "") + ">" +
document.getElementById("table").innerHTML + str[b] +
"</td>";
}
t += "</tr>";
}
function changeColor() {
var letter = document.getElementById("matching").value;
for (i = 0; i < 5; i++) {
if (letter == str[i]) {
return true;
}
}
return false;
}
I would make a demo, but I have no idea about the HTML.
This is an example that might help you:
<html>
<head>
<style>
td {
border: 2px solid green;
padding: 30px;
}
.yellowColor{
background-color: yellow;
}
</style>
</head>
<body>
Enter Letter : <input type="text" id="matching">
<br><br>
<table id="tab">
<tr>
<td>a</td><td>b</td></tr>
<tr><td>c</td><td>f</td></tr>
<tr><td>b</td><td>a</td></tr>
</table>
<script>
var tds = document.getElementsByTagName("td");
var ele= document.getElementById("matching");
ele.onkeyup =function(){changeColor();}
function changeColor() {
var i = 0;
var letter = ele.value;
for(i; i<tds.length;i++) {
if(tds[i].innerHTML == letter){
tds[i].style.backgroundColor = "yellow";
//OR use this code;
//tds[i].classList.add("yellowColor");
}
else
tds[i].style.backgroundColor = "";
}
}
</script>
</body>
</html>

Categories

Resources