Cant see why this JavaScript-code won't run - settimeout

I'm new to JavaScript and have written this code. It worked before, but now it just don't, and I don't understand why. The text on the button doesn't even change to "PAUSE". When I try it in the browser it says after a while that "localhost is not responding due to a long-running script."
<div>
<div id="tabataBox">
<p id="PauseGoText"></p>
<p id="stopwatch">CLICK TO START WORKOUT</p>
<button id="tabataButton" onclick="startPause()">START</button>
</div>
<span class="circle" id="el-1"></span>
<span class="circle" id="el-2"></span>
<span class="circle" id="el-2"></span>
<span class="circle" id="el-3"></span>
<span class="circle" id="el-4"></span>
<span class="circle" id="el-5"></span>
<span class="circle" id="el-6"></span>
<span class="circle" id="el-7"></span>
<span class="circle" id="el-8"></span>
</div>
</div>
var time = 0;
var running = 0;
var everySecond = true;
var max = 20;
var numberOfTimes = 1;
function startPause() {
if (running == 0) {
running = 1;
document.getElementById("tabataButton").innerHTML = "PAUSE";
increment();
}
else {
running = 0;
document.getElementById("tabataButton").innerHTML = "START";
}
}
function reset() {
time = 1;
document.getElementById("stopwatch").innerHTML = "0";
if (everySecond == true)
{
everySecond = false;
max = 20;
document.getElementById("tabataBox").style.backgroundColor = "green";
document.getElementById('el-'+numberOfTimes).style.backgroundColor = "green";
numberOfTimes++;
document.getElementById("PauseGoText").innerHTML = "REST";
}
else {
everySecond = true;
max = 10;
document.getElementById("tabataBox").style.backgroundColor = "red";
document.getElementById("PauseGoText").innerHTML = "GO!";
}
}
function increment() {
if (running == 1) {
setTimeout(function () {
time++;
if (time > max) {
reset();
}
document.getElementById("stopwatch").innerHTML = time;
increment();
}, 1000)
}
}

Related

I have tried a pagination in LWC

I have tried a pagination to display my accounts. The issue I found with the below code is when i click on 2, the list is iterating and display one more array list. At first, it looks 1 2 3 4 5 when i click on any number it displays as 1 2 3 4 2 3 4 5 and on another click 1 2 3 4 2 3 4 2 3 4 5. Basically, it displays the arraylist one more to the original one.
html:
<template>
<lightning-card title="Pagination on Account">
<div class="slds-var-m-around_medium">
<template if:true={showAccounts}>
<template for:each={showAccounts} for:item="a">
<p key={a.Id}>{a.Name}</p>
</template>
</template>
</div>
<lightning-layout>
<lightning-layout-item padding="around-small" flexibility="auto">
<div class="slds-grid slds-wrap">
<lightning-button icon-name="utility:chevronleft" icon-position="left" onclick={prev}></lightning-button>
<span class="slds-p-horizontal_x-small" title="Display">
<a onclick={processMe} name="1"
class={displayPageNumber}>1</a>
</span>
<template for:each={pageList} for:item="item">
<div key={item.Id}>
<span class="slds-p-horizontal_x-small" title="DisplayMore">
<a onclick={processMe} name={item}
class={displaymore}>{item}</a>
</span>
</div>
</template>
<span class="slds-p-horizontal_x-small" title="Display">
<a onclick={processMe} name={totalPage}
class={displayTotalPage}>{totalPage}</a>
</span>
<lightning-button icon-name="utility:chevronright" icon-position="right" onclick={next}></lightning-button>
</div>
</lightning-layout-item>
</lightning-layout>
</lightning-card>
</template>
.js
import { LightningElement,wire,track } from 'lwc';
import getAccounts from '#salesforce/apex/PaginationonAccounts.getAccounts';
export default class PaginationonAccounts extends LightningElement {
totalAccounts;
currentPageNumber = 1;
showAccounts;
pageSize = 10;
pageList = [];
item;
totalPage = 0;
#wire(getAccounts)
wiredAccounts({data,error}) {
if(data)
{
this.totalAccounts = data;
console.log('Total Accounts',this.totalAccounts);
this.totalPage = Math.ceil(data.length/this.pageSize);
this.currentPageNumber = 1;
this.buildData();
}
}
prev(event)
{
if(this.currentPageNumber > 1)
{
console.log('Previous');
this.currentPageNumber = this.currentPageNumber-1;
this.buildData();
}
}
processMe(event)
{
console.log('Process me');
this.currentPageNumber = parseInt(event.target.name);
console.log('Process me Page Number',this.currentPageNumber);
this.buildData();
}
next(event)
{
if(this.currentPageNumber < this.totalPage)
{
this.currentPageNumber = this.currentPageNumber+1;
this.buildData();
}
}
//to display pageNumbers
get displayPageNumber()
{
if(this.currentPageNumber == 1)
{
return 'selected';
}
else
{
return '';
}
}
//to display more pageNumbers
get displaymore()
{
if(this.currentPageNumber === this.item)
{
return 'selected';
}
else
{
return '';
}
}
//to display totalPage
get displayTotalPage()
{
if(this.currentPageNumber == this.totalPage)
{
return 'selected';
}
else
{
return '';
}
}
buildData()
{
console.log('Build data');
var data = [];
var pageNumber = this.currentPageNumber;
var pageSize = this.pageSize;
var totalAccounts = this.totalAccounts;
var x = (pageNumber-1)*pageSize;
for(; x<=(pageNumber)*pageSize; x++)
{
if(totalAccounts[x])
{
data.push(totalAccounts[x]);
}
}
this.showAccounts = data;
this.generatePageList(pageNumber);
}
generatePageList(pageNumber)
{
pageNumber= parseInt(pageNumber);
console.log('Page Number',pageNumber);
//this.pageList = [];
if(this.totalPage > 1)
{
if(this.totalPage <= 10)
{
var counter = 2;
for(; counter < (this.totalPage); counter++)
{
this.pageList.push(counter);
}
}
else
{
if(pageNumber < 5)
{
this.pageList.push(2,3,4,5,6);
}
else
{
if(pageNumber>(this.totalPage-5)){
this.pageList.push(this.totalPage-5, this.totalPage-4,
this.totalPage-3, this.totalPage-2, this.totalPage-1);
} else{
this.pageList.push(pageNumber-2, pageNumber-1, pageNumber,
pageNumber+1, pageNumber+2);
}
}
}
}
}
}
css
.THIS .selected{
color:orange;
}

MVC app does not show selected values on a form reedition

I am building a Framework7 MVC app and found myself in a dead end alley. I have a form which I need to evaluate. This form contains selects. I am using localStorage to store the form values and everything works OK in that sense, I mean everything is stored correctly. ¿What is the issue? When I fill the form I answer some questions on textareas inputs, select inputs and inputs. everything goes fine until I try to reedit the form, then everything is display correctly on the form, including the score i got from my previous answers, but, the selects appears as if I have never touch them. Their previously selected value is stored but not display on the form. I have found that the issue is caused by the fact that I have set numerical values to the options values but what the form show is "yes" or "no". If I change the option values to "yes" or "no" then the form displays correctly but I need to set "5" or "0" because I need to evaluate the user's answers.
This is my code
The form
<li style="margin-top:-10px;">
<input style="visibility:hidden;height:1px;" value="0" name="choice" onchange="checkTotal()"/>
<input style="visibility:hidden;height:1px;" value="1" type="checkbox" name="choice" onchange="checkTotal()" checked="on">
</li>
<li><div class="item-content">1. ¿Sueles quejarte de sentirte mal?</div>
<div class="item-content">
<div class="item-inner">
<div class="item-input">
<select name="pr1" id="pr1" onchange="checkTotal()">
<option class="item-inner" value="5">No</option>
<option class="item-inner" value="0">Si</option>
</select>
</div>
</div>
</div>
<div class="item-content">En tal caso,</div>
<div class="item-content">
<div class="item-inner">
<div class="item-input">
<textarea class="resizable" id="pr1notes" placeholder="¿cuál es la causa?">{{model.pr1notes}}</textarea>
</div>
</div>
</div>
</li>
The functions on the editController
function init(query){
var protections = JSON.parse(localStorage.getItem("f7Protections"));
if (query && query.id) {
protection = new Protection(_.find(protections, { id: query.id }));
state.isNew = false;
}
else {
protection = new Protection({ isFavorite: query.isFavorite });
state.isNew = true;
}
View.render({ model: protection, bindings: bindings, state: state, doneCallback: saveProtection });
showSelectedValues();
}
function showSelectedValues(){
var fieldNames = protection.getSelectFields();
for (var i = 0, len = fieldNames.length; i < len; i++) {
var itemname = fieldNames[i];
var selectObj = document.getElementById(itemname);
if (selectObj!=null) {
var objOptions = selectObj.options;
var selIndex=0;
for (var j = 0, len2 = objOptions.length; j < len2; j++) {
if ((objOptions[j].label).localeCompare(protection[itemname])==0){
selIndex=j;
}
}
selectObj.options[selIndex].setAttribute("selected","selected");
}else{
}
}
}
and the model
Protection.prototype.setValues = function(inputValues, extras) {
for (var i = 0, len = inputValues.length; i < len; i++) {
var item = inputValues[i];
if (item.type === 'checkbox') {
this[item.id] = item.checked;
}
else {
this[item.id] = item.value;
}
}
for (var i = 0, len = extras[0].length; i < len; i++) {
var item = extras[0][i];
if((item.id).localeCompare("pr1notes")==0) {this[item.id] = item.value;}
}
console.log('starting loop for extras 3...');
for (var i = 0, len = extras[2].length; i < len; i++) {
var item = extras[2][i];
this[item.name] = item.value;
}
};
Protection.prototype.validate = function() {
var result = true;
if (_.isEmpty(this.prdate)
) {result = false;}
return result;
};
Protection.prototype.getSelectFields = function() {
return ['pr1'];
}
What should I change in order to keep my "5" or "0" values on the select options while the form options still show "yes" or "no" to the user just like this: <select name="pr1" id="pr1" onchange="checkTotal()"><option class="item-inner" value="5">No</option><option class="item-inner" value="0">Si</option></select>?
need anything else to help you understand the issue?
The simplest solution
function init(query){
var protections = JSON.parse(localStorage.getItem("f7Protections"));
if (query && query.id) {
protection = new Protection(_.find(protections, { id: query.id }));
state.isNew = false;
}
else {
protection = new Protection({ isFavorite: query.isFavorite });
state.isNew = true;
}
View.render({ model: protection, bindings: bindings, state: state, doneCallback: saveProtection });
showSelectedValues();
}
function showSelectedValues(){
var fieldNames = protection.getSelectFields();
for (var i = 0, len = fieldNames.length; i < len; i++) {
var itemname = fieldNames[i];
var selectObj = document.getElementById(itemname);
if (selectObj!=null) {
var objOptions = selectObj.options;
var selIndex=0;
for (var j = 0, len2 = objOptions.length; j < len2; j++) {
if ((objOptions[j].value).localeCompare(protection[itemname])==0){
selIndex=j;
}
}
selectObj.options[selIndex].setAttribute("selected","selected");
}else{
}
}
}
Just changed this line
if ((objOptions[j].label).localeCompare(protection[itemname])==0){
selIndex=j;
and changed .label for .value.

Extending Dynamic-forms from angular2 cookbook to be able to have arrays

I have tried to extend the Dynamic-Forms app from angular 2 cookbook so I can have an array of multiple fields. I have been able to show the fields, but when I'm filling the form, I'm getting just the last element of the array filled.
Hier is my plunker with that state of the app:
//question-array.ts
import { QuestionBase } from './question-base';
export class ArrayQuestion extends QuestionBase<string> {
controlType = 'array';
options:{childe:FormElement<string>}[] = [];
constructor(options:{} = {}){
super(options);
this.options = options['options'] || [];
}
}
//question-control.service.ts
...
toFormGroup(formelements: QuestionBase<any>[] ) {
let group:any = {};
formelements.forEach(element => {
console.log("+element",element);
if(element.controlType === "array"){
let arr:any[] = [];
let locobj = {};
element["options"].forEach((option:any) => {
option["element"].forEach((e:any) =>{
locobj[e.key] = new FormControl(e.value || '');
});
arr.push(new FormGroup(locobj))
});
group[element.key] = new FormArray(arr);
}else{
group[element.key] = element.required ? new FormControl(element.value || '', Validators.required)
: new FormControl(element.value || '');
}
});
return new FormGroup(group);
}
//dynamic-form-question.component.html
...
<div *ngSwitchCase="'array'" [formArrayName]="question.key">
<div *ngFor="let item of question.options; let i=index" [formGroupName]="i" >
<div *ngFor="let element of item.element">
<div *ngIf="element.controlType === 'textbox'" >
<label>{{element.label}}</label>
<input [formControlName]="element.key" [id]="element.key" [type]="element.type" />
</div>
<div *ngIf="element.controlType === 'dropdown'" >
<label>{{item.label}}</label>
<select [id]="element.key" [formControlName]="element.key">
<option *ngFor="let opt of element.options" [value]="opt.key">{{opt.value}}</option>
</select>
</div>
</div>
</div>
</div>
...
http://plnkr.co/edit/DZ05fO
Best regard,
Shefki
I found the bug, the problem was that I was passing the same reference in the form group her is what i changed:
//question-control.service.ts
toFormGroup(formelements: QuestionBase[] ) {
let group:any = {};
formelements.forEach(element => {
if(element.controlType === "array"){
let arr:any[] = [];
let locobj = {};
element["options"].forEach((option:any) => {
option["element"].forEach((e:any) =>{
locobj[e.key] = e.value || '';
});
arr.push(new FormGroup(this.getFormControlObject(locobj)));
});
group[element.key] = new FormArray(arr);
}else{
group[element.key] = element.required ? new FormControl(element.value || '', Validators.required)
: new FormControl(element.value || '');
}
});
return new FormGroup(group);
}
private getFormControlObject(keys){
let retobj = {};
Object.keys(keys).forEach(function(key) {
retobj[key] = new FormControl(keys[key]);
});
return retobj;
}
Hier is a working plunker
http://plnkr.co/edit/4IMKdLKE51n41jzYY8sU

Google Maps API GeoLocation not working for mobile

I'm not really sure why the GeoLocation works on my PC, but not my iPhone ... I've got sensor=true within the script call to the API, but apart from that, I'm at a loss. Here's the entire script:
<div id="info"></div>
<div id="map_canvas" style="width:908px; height:420px"></div>
<input type="text" id="addressInput" size="10"/>
<select id="radiusSelect">
<option value="5" selected>5mi</option>
<option value="15" selected>15mi</option>
<option value="25" selected>25mi</option>
<option value="100">100mi</option>
<option value="200">200mi</option>
<option value="4000">4000mi</option>
</select>
<input type="button" value="Search" onclick="searchLocations();">
<div><select id="locationSelect" style="width:100%;visibility:hidden"></select></div>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCe49sI29q0AVNo9iVvQ-lDlDwZpFZuA4o&sensor=true"></script>
<script type="text/javascript" src="http://gmaps-samples-v3.googlecode.com/svn/trunk/geolocate/geometa.js"></script>
<script type="text/javascript">
var map;
var markers = [];
var infoWindow;
var locationSelect;
function load() {
map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
infoWindow = new google.maps.InfoWindow();
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none") {
google.maps.event.trigger(markers[markerNum], 'click');
}
};
// geolocation
prepareGeolocation();
doGeolocation();
}
function doGeolocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(positionSuccess, positionError);
} else {
positionError(-1);
}
}
function positionError(err) {
var msg;
switch(err.code) {
case err.UNKNOWN_ERROR:
msg = "Unable to find your location";
break;
case err.PERMISSION_DENINED:
msg = "Permission denied in finding your location";
break;
case err.POSITION_UNAVAILABLE:
msg = "Your location is currently unknown";
break;
case err.BREAK:
msg = "Attempt to find location took too long";
break;
default:
msg = "Location detection not supported in browser";
}
document.getElementById('info').innerHTML = msg;
}
function positionSuccess(position) {
// Centre the map on the new location
var coords = position.coords || position.coordinate || position;
var latLng = new google.maps.LatLng(coords.latitude, coords.longitude);
map.setCenter(latLng);
map.setZoom(15);
var marker = new google.maps.Marker({
map: map,
position: latLng,
title: 'Why, there you are!'
});
document.getElementById('info').innerHTML = 'Looking for <b>' +
coords.latitude + ', ' + coords.longitude + '</b>...';
// And reverse geocode.
(new google.maps.Geocoder()).geocode({latLng: latLng}, function(resp) {
var place = "You're around here somewhere!";
if (resp[0]) {
var bits = [];
for (var i = 0, I = resp[0].address_components.length; i < I; ++i) {
var component = resp[0].address_components[i];
if (contains(component.types, 'political')) {
bits.push('<b>' + component.long_name + '</b>');
}
}
if (bits.length) {
place = bits.join(' > ');
}
marker.setTitle(resp[0].formatted_address);
}
document.getElementById('info').innerHTML = place;
});
}
function contains(array, item) {
for (var i = 0, I = array.length; i < I; ++i) {
if (array[i] == item) return true;
}
return false;
}
function searchLocations() {
console.log("searching locations...");
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location);
} else {
alert(address + ' not found');
}
});
}
function clearLocations() {
//infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
locationSelect.innerHTML = "";
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
locationSelect.appendChild(option);
locationSelect.style.visibility = "visible";
}
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
/* var searchUrl = 'phpsqlajax_search.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius; */
var searchUrl = 'http://dev-imac.local/phpsqlajax_search.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
console.log(searchUrl);
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createOption(name, distance, i);
createMarker(latlng, name, address);
bounds.extend(latlng);
}
map.fitBounds(bounds);
});
}
function createMarker(latlng, name, address) {
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name + "(" + distance.toFixed(1) + ")";
locationSelect.appendChild(option);
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
window.onload = load();
</script>
First of all,
mapTypeId: 'roadmap',
should be:
mapTypeId: google.maps.MapTypeId.ROADMAP,
but that should cause it to fail in your PC as well.
Other than that, your <script> section should be in the <head> section of the document and not in the <body>. Maybe the iPhone browser is more strict about this than the browser on your PC. What browser(s) are you using in each system? (I'm guessing you're using IE on the PC. Have you tried other browsers?)

Select rows with checkbox in SlickGrid

I need to make a column where you can select grid rows with input:checkbox. Grids like ones used by Yahoo, Google etc have something like that.
I made something but I have some problems and I think that is not a good aproach also.
It's posible to have checkboxes in rows and click on them directly, not like in example4-model ?
My idea was :
< div id="inlineFilterPanel" class="slick-header-column" style="padding: 3px 0; color:black;">
<input type="checkbox" name="selectAll" id="selectAll" value="true" / >
< input type="text" id="txtSearch2" value="Desktops" />
</div>
d["check"] = '< INPUT type=checkbox value='true' name='selectedRows[]' id='sel_id_<?php echo $i; ?>' class='editor-checkbox' hideFocus />';
grid.onSelectedRowsChanged = function() {
selectedRowIds = [];
$('#myGrid' + ' :checkbox').attr('checked', '');
var rows = grid.getSelectedRows();
for (var i = 0, l = rows.length; i < l; i++) {
var item = dataView.rows[rows[i]];
if (item) {
selectedRowIds.push(item.id);
$('#sel_' + item.id).attr('checked', 'checked');
}
}
};
function selectAllRows(bool) {
var rows = [];
selectedRowIds = [];
for (var i = 0; i < dataView.rows.length; i++) {
rows.push(i);
if (bool) {
selectedRowIds.push(dataView.rows[i].id);
$('#sel_' + dataView.rows[i].id).attr('checked', 'checked');
} else {
rows = [];
$('#sel_' + dataView.rows[i].id).attr('checked', '');
}
}
grid.setSelectedRows(rows);
}
grid.onKeyDown = function(e) {
// select all rows on ctrl-a
if (e.which != 65 || !e.ctrlKey)
return false;
selectAllRows(true);
return true;
};
$("#selectAll").click(function(e) {
Slick.GlobalEditorLock.cancelCurrentEdit();
if ($('#selectAll').attr('checked'))
selectAllRows(true);
else
selectAllRows(false);
return true;
});
Thanks!
I've added a sample implementation of a checkbox select column to http://mleibman.github.com/SlickGrid/examples/example-checkbox-row-select.html
This is part of the upcoming 2.0 release.