using checkboxes and counting them in Lightswitch HTML - javascript

I am currently using this code to display checkboxes as a custom control, and it works perfect:
// Create the checkbox and add it to the DOM.
var checkbox = $("<input type='checkbox'/>")
.css({
height: 20,
width: 20,
margin: "10px"
})
.appendTo($(element));
// Determine if the change was initiated by the user.
var changingValue = false;
checkbox.change(function () {
changingValue = true;
contentItem.value = checkbox[0].checked;
changingValue = false;
});
contentItem.dataBind("value", function (newValue) {
if (!changingValue) {
checkbox[0].checked = newValue;
}
});
however now I want to extend this a little, and I am wondering if anyone knows how I can count values based on whether they are true or false.
What im looking for:
I have 2 checkboxes below, the 1st is "TRUE" and the 2nd is "FALSE"
I want to be able to count up these values using something like var count then put it in a while loop, or an array and then display it back on a button like the following for testing purposes: window.alert("add in text here" + add_code_here)
so example data would be:
var trueCount = 0;
var falseCount = 0;
window.alert("There are: " + trueCount + " values that are true and " + falseCount + " that are false");
and the above example trueCount = 1 and falseCount = 1
Thanks for any input people can give me, it is most appreciated

I couldn't get it to work with the custom control check boxes but for the standard switches this code worked for me:
var trueCount = 0;
var falseCount = 0;
myapp.TableName.ColumnName_postRender = function (element, contentItem) {
// count the true or false values
contentItem.dataBind("value", function (newValue) {
if (contentItem.value == true) {
trueCount ++;
falseCount--;
} else if (contentItem.value == false) {
falseCount++;
trueCount--;
}
});
//count 3 sets both trueCount and falseCount to 0 as they would already be affected by the
//post render method. This works by adding or subtracting the amount of false values non
//screen (works my my scenario)
var count3 = 0;
if (contentItem.value == false) {
count3++;
}
falseCount = falseCount - count3;
trueCount = trueCount + count3;
};
myapp.TableName.Save_execute = function (screen) {
window.alert("True Count: " + trueCount + " | falseCount: " + falseCount);
//set both count values back to 0 for when the screen is next run
trueCount = 0;
falseCount = 0;
}

Related

Nesting a function returning NaN

I am running into an error when I try nesting a simple counter function inside an existing function. I know some people frown upon this, so if there is any other way of doing this, it would be greatly appreciated. Basically, I am calling a function to parse a JSON string to get 3 numbers. I would like to animate those 3 numbers with a counter every time a new calculation is made. My instinct is to place this counter function inside of the same for loop that runs to get the numbers themselves. Doing so returns NaN. I'm sure there is something very little that I am missing here that I am hoping someone can pick up on.
Code:
var text = '{JSON data}'
var obj = JSON.parse(text);
function calculate() {
var e = document.getElementById("ltSpecialtyList");
var selectedSpec = e.options[e.selectedIndex].text;
console.log(selectedSpec);
var x = document.getElementById("ltLocationList");
var selectedState = x.options[x.selectedIndex].text;
console.log(selectedState);
for (i = 0; i < obj.values.length; i++)
{
if (obj.values[i].State == selectedState && obj.values[i].Specialty == selectedSpec)
{
// DISPLAY RESULTS DIV (JQUERY)
var $resultsDiv = $("#ROI-results");
$resultsDiv.fadeIn();
// CAPTURE HEADER SPAN NAMES
var headerState = document.getElementById("header-state-name");
var headerSpec = document.getElementById("header-specialty-name");
// CLEAR STATE AND SPECIALTY FROM SPAN
headerState.innerHTML = "";
headerSpec.innerHTML = "";
// ADD SELECTED STATE AND SPECIALTY
headerState.innerHTML += selectedState;
headerSpec.innerHTML += selectedSpec;
// CAPTURE RESULT DATA DIVS
var permResults = document.getElementById("ROI-results-perm-data");
var locumResults = document.getElementById("ROI-results-locums-data");
var uncollectedResults = document.getElementById("ROI-results-uncollected-data");
// CLEAR DATA DIVS
permResults.innerHTML = "";
locumResults.innerHTML = "";
uncollectedResults.innerHTML = "";
//POPULATE DIV WITH DATA
permResults.innerHTML += "<p class='ROI-results-data-number univers-bold'>" + obj.values[i].Permanent + "</p>";
locumResults.innerHTML += "<p class='ROI-results-data-number univers-bold'>" + obj.values[i].Locums + "</p>";
uncollectedResults.innerHTML += "<p class='ROI-results-data-number univers-bold'>" + obj.values[i].Gross + "</p>";
}
// COUNTER
$('.ROI-results-data-number').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
}
}

Getting an infinite loop and can't see why - Javascript

I'm writing a simple little Connect 4 game and I'm running into an infinite loop on one of my functions:
var reds = 0;
var greens = 0;
function checkEmpty(div) {
var empty = false;
var clicked = $(div).attr('id');
console.log(clicked);
var idnum = parseInt(clicked.substr(6));
while (idnum < 43) {
idnum = idnum + 7;
}
console.log("idnum=" + idnum);
while (empty == false) {
for (var i = idnum; i > 0; i - 7) {
idnumStr = idnum.toString();
var checking = $('#square' + idnumStr);
var str = checking.attr('class');
empty = str.includes('empty');
console.log(empty);
var divToFill = checking;
}
}
return divToFill;
}
function addDisc(div) {
if (reds > greens) {
$(div).addClass('green');
greens++;
console.log("greens=" + greens);
} else {
$(div).addClass('red');
reds++;
console.log("reds=" + reds);
};
$(div).removeClass('empty');
}
$(function() {
var i = 1;
//add a numbered id to every game square
$('.game-square').each(function() {
$(this).attr('id', 'square' + i);
i++;
//add an on click event handler to every game square
//onclick functions
$(this).on('click', function() {
var divToFill = checkEmpty(this);
addDisc(divToFill);
})
})
})
Here is a link to the codepen http://codepen.io/Gobias___/pen/xOwNOd
If you click on one of the circles and watch the browser's console, you'll see that it returns true over 3000 times. I can't figure out what I've done that makes it do that. I want the code to stop as soon as it returns empty = true. empty starts out false because I only want the code to run on divs that do not already have class .green or .red.
Where am I going wrong here?
for (var i = idnum; i > 0; i - 7);
You do not change the i.
Do you want to decrement it by 7?
Change your for loop to the one shown below:
for (var i = idnum; i > 0; i -= 7) {
// ...
}
You also do not use loop variable in the loop body. Instead, you use idnum, I think this can be issue.
while (empty == false) {
for (var i = idnum; i > 0; i -= 7) {
idnumStr = i.toString(); // changed to i
var checking = $('#square' + idnumStr);
var str = checking.attr('class');
empty = str.includes('empty');
console.log(empty);
var divToFill = checking;
// and don't forget to stop, when found empty
if (empty) break;
}
}
I add break if empty found, because if we go to next iteration we will override empty variable with smallest i related value.
You can also wrap empty assignment with if (!empty) {empty = ...;} to prevent this override, but I assume you can just break, because:
I want the code to stop as soon as it returns empty = true
Offtop hint:
while (idnum < 43) {
idnum = idnum + 7;
}
can be easy replaced with: idnum = 42 + (idnum%7 || 7)
Change to this:
for (var i = idnum; i > 0; i = i - 7) {
You are not decrementing the i in your for loop
Building on what the others have posted You would want to change the value of empty inside the for loop. because obviously the string still checks the last string in the loop which would always return false.
while(empty==false){
for (var i = idnum; i > 0; i -= 7) {
// your other codes
if (!empty) {
empty = str.includes('empty');
}
}

Loop through multiple select lists and count the number of times each option is selected

Part of a site I'm working on involves creating repeat instances of the same select - option. I would like to count the number of times each option has been selected, and then store that number as a variable, which can then be sent to php email function.
For example - if "Infallid" is selected 3 times - I get infallid = 3, and 0 for the others.
JS fiddle showing how it all works - https://jsfiddle.net/scx4shnd/2/
$("button").click(function(){
$("select[name='diskho'] > option:selected").each(function() {
alert(this.text + ' ' + this.value);
// should alert - "value 1 = x" , "value 2 = "y" ect" where x and y are different values (numbers)
});
$("select[name='spishall'] > option:selected").each(function() {
alert(this.text + ' ' + this.value);
});
});
You can use following logic to calculate the number of times an option has been selected:
$("button").click(function(){
var dishkoMap = {};
$("select[name='diskho'] > option:selected").each(function () {
var value = this.value;
if (dishkoMap[value]) { // if value already exists then increase it by 1
dishkoMap[value] += 1;
} else {
dishkoMap[value] = 1;
}
});
// dishkoMap is a dictionary object so you won't see anything in alert.
// open the browser console and you can see the counts corresponding
// to each selected option
console.log(dishkoMap);
});
Similarly, you can also write for Spishäll and Blandare.
I would suggest writing a function where you pass the name of the select and then return the countMap.
function getCountMap(name) {
var countMap = {};
$("select[name='" + name + "'] > option:selected").each(function () {
var value = this.value;
if (countMap[value]) { // if value already exists then increase it by 1
countMap[value] += 1;
} else {
countMap[value] = 1;
}
});
return countMap;
}
and then use it as:
var dishkoMap = getCountMap('dishko');
var spishallMap = getCountMap('spishall');
// etc.

jQuery Pagination next and previous buttons fail after hitting zero or past last page

previous and Next buttons don't have limitations, ie: can move before and after first and last pages... cant seem to limit this.
I've created if statements to try and stop the button from executing but it wont work. any ideas?
jsFiddle: https://jsfiddle.net/s7ac8aq3/
$(function() {
$(document).ready(function(){
//amount of items on page
var num = $('.post').length;
//set items per page
var itemsPerPage = 1;
var nav = false;
//array of all items
var items = $(".post");
//rounds up to the nearest whole number -- number of pages needed to display all results
var numOfPages = Math.ceil((num / itemsPerPage));
//container div
var paginationContainer = $("#pagination-container");
//initial link num
var linkNum = 1;
paginationContainer.prepend("<button class='pagination' id='btn-prev' value='prev'>Prev</button>");
//creates all pagination links as input buttons (can be anything... li, a, div, whatever)
for(i = 0; i < numOfPages; i++)
{
paginationContainer.append("<button class='pagination' id='btn-" + (i + 1) +"' " + "value='" + (i + 1) + "'>" + (i + 1) + "</button>");
}
paginationContainer.append("<button class='pagination' id='btn-next' value='next'>Next</button>");
//does the initial filtering of the items, hides anything greater than page 1
items.filter(":gt(" + (itemsPerPage -1) + ")").hide();
//finds the input feilds and executes onclick
paginationContainer.find('button').on('click', function(){
//REQUIRED RESETS NAV BOOL SO CLICKS WILL REGISTER
nav = false;
//stores the value of the link in this var
var val = $(this).val();
//if value is next or prev
if(val == "prev")
{
if(linkNum > 1)
{
nav = true;
linkNum = linkNum - 1;
var currentBtn = paginationContainer.find("#btn-" + linkNum);
var otherButtons = paginationContainer.find('button');
otherButtons.attr('class', "pagination");
currentBtn.attr('class', "current");
currentBtn.focus();
}
}
else if (val == "next")
{
if(linkNum < numOfPages)
{
nav = true;
linkNum = linkNum + 1;
var currentBtn = paginationContainer.find("#btn-" + linkNum);
var otherButtons = paginationContainer.find('button');
otherButtons.attr('class', "pagination");
currentBtn.attr('class', "current");
currentBtn.focus();
}
}
if(nav == false)
{
//reoves the current class from all buttons before reassigning
var otherButtons = paginationContainer.find('button');
linkNum = $(this).val();
otherButtons.attr('class', "pagination");
//assigns current class to current button
$(this).attr("class", "current");
}
//creates an array of items to hide based on if the set results are less than the link num
var itemsToHide = items.filter(":lt(" + ((linkNum-1) * itemsPerPage) + ")");
// adds any items that are greater than the set results from the link num to the hide array
$.merge(itemsToHide, items.filter(":gt(" + ((linkNum * itemsPerPage) -1) + ")"));
// hides the items in hide array
itemsToHide.hide();
//shows all items NOT in the hide array
var itemsToShow = items.not(itemsToHide);
itemsToShow.show();
});
});
});
A little debugging of your jsFiddle identified the problem. In this part of the code:
} else if (val == "next") {
if (linkNum < numOfPages) {
nav = true;
linkNum = linkNum + 1;
the value of linkNum is sometimes being stored as a string. As a result, adding "3"+1 produces "31" in JavaScript.
The trivial solution is to convert it to an integer before the addition:
linkNum = parseInt(linkNum,10) + 1; // always use a radix
https://jsfiddle.net/mblase75/s7ac8aq3/3/
However, I would instead prefer to solve the problem at its source, a few lines down:
if (nav == false) {
var otherButtons = paginationContainer.find('button');
linkNum = $(this).val();
When you store linkNum in the first place, .val() returns a string. Parse it as an integer right away:
linkNum = parseInt($(this).val(),10);
https://jsfiddle.net/mblase75/s7ac8aq3/4/
and then you don't have to change it before performing the addition.
Your problem in linkNum variable, when you click on certain page number, variable gets a string value, after that when you trying to add 1 you receive a new string, for example "3" + 1 => "31", "4" + 1 => "41"

keeping a innerhtml value from a javascript after a html form submit

I am using below javascript to collect values from some textboxes,do some calculations and display the result as a innerhtml content
window.onload = function () {
var left = document.getElementById('mem_count');
var right = document.getElementById('siz_single');
var result = document.getElementById("disp_siz");
function check(a, b, elem) {
var txt = '';
if (a === 0 && b === 0) {
}
else if (a !== 0 && b === 0) {
txt = "Enter size of single device in above column"
}
else if(a == 0 && b !== 0){
txt = "Enter Meta member count in above column "
}
else {
var c = 1 +a
txt = "Your meta device size is " + (c*b) +" MB" + " = " + (c*b/1024) +" GB ";
}
disp_siz.innerHTML = txt;
}
mem_count.onkeyup = calc;
siz_single.onkeyup = calc;
function calc() {
var a = parseFloat(mem_count.value) || 0;
var b = parseFloat(siz_single.value) || 0;
check(a,b, this);
}
}
and the output will be display in between the div
<div id="disp_siz"><-----above output will come here----></div>
This div is part of a html form. I am able to keep all my other form values in same field after form submission. But not able to display above output. It just clearing my values. Is there anyway I can echo this javascript variable value to the same field after form submision ?
First Option:
Set it on the serverside.
Second Option:
If the page refreshes, it is like cleaning a whiteboard, you got to start over. If the fields are there, trigger the function to run.
Add calc(); to the end of the onload function.
...
...
function calc() {
var a = parseFloat(mem_count.value) || 0;
var b = parseFloat(siz_single.value) || 0;
check(a,b, this);
}
calc(); //<-- added this to trigger the calculation
}
Another problem:
And you should not reference an element by their id directly. You should use
document.getElementById("disp_siz").innerHTML = txt;
You're referencing a variable (disp-siz) that doesn't exist. Use the variable you created earlier, result.
result.innerHTML = txt;

Categories

Resources