We help IT Professionals succeed at work.

JavaScript

123K

Solutions

42K

Contributors

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and  in almost every mainstream web browser.

hi am having error running my nodejs








PS C:\Angular3\mean-course> node server.js
C:\Angular3\mean-course\server.js:47
app.set("port", port);
    ^

TypeError: app.set is not a function
    at Object.<anonymous> (C:\Angular3\mean-course\server.js:47:5)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
PS C:\Angular3\mean-course> npm install
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\webpack-dev-server\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\watchpack\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2
0
What would be the regex for combining ( the regex below) "qa" or "test" coming before ",cmo")

(qa\.cmo|test\.cmo)

so test.cmo and qa.cmo will be identified without making the two different regexs as in my example?
1
Here's my initial code:

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    'Access-Control-Allow-Methods',
    'GET, POST, PUT, PATCH, DELETE'
  );
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
  next();
});

Open in new window


This is part of a Node.js tutorial I'm going through. It's a React front end that interacts with an API which utilizes GraphQL.

The code that I've got above is from the "app.js" file that's a part of the API. I've got the code in its entirety below:

const path = require("path");

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const multer = require("multer");
const graphqlHttp = require('express-graphql');

const graphqlSchema = require('./graphql/schema');
const graphqlResolver = require('./graphql/resolvers');

const app = express();

const fileStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "images");
  },
  filename: (req, file, cb) => {
    //cb(null, uuidv4());
    cb(null, file.originalname);
  }
});

const fileFilter = (req, file, cb) => {
  if (
    file.mimetype === "image/png" ||
    file.mimetype === "image/jpg" ||
    file.mimetype === "image/jpeg"
  ) {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

app.use(bodyParser.json());
app.use(
  multer({
    storage: fileStorage,
    fileFilter: fileFilter
  }).single("image")
);

Open in new window

0
hi am having error in my angular component
todos
import { Component, OnInit } from '@angular/core';
import { TodoDataService } from '../service/data/service/data/todo-data.service';


export class Todo {
  constructor(
    public id: number,
    public description: string,
    public done: boolean,
    public targetDate: Date
  ){

  }
}


@Component({
  selector: 'app-list-todos',
  templateUrl: './list-todos.component.html',
  styleUrls: ['./list-todos.component.css']
})
export class ListTodosComponent implements OnInit {

   todos = Todo
  //   new Todo(1,'Learn to Dance',false,new Date()),
  //   new Todo(2,'Become Expert in angualr',false,new Date()),
  //   new Todo(3,'Visit South Africa',false,new Date())

    //  {id : 1,description :'Learn to Dance'},
    //  {id : 2,description :'Become an Expert in Angular'},
    //  {id : 3,description :''},
  
//  ]
    
  // todo = {
  //      id : 1,
  //      description: 'Learn to dance'

  // }

  constructor(private todoservice:TodoDataService ) { }

  ngOnInit() {
    this.todoservice.retriveAllTodos('tshifhiwa')
    .subscribe( 
        response => 
            { 
                console.log(response); 
                this.todos = response; 
            } 
    )
}
}
   

Open in new window

0
I am getting the following error in my JS file, "Uncaught SyntaxError: Missing initializer in const declaration" on line 13,14.

The function determines a users' state based on phone-number entered on an html form.

function getState(arecode) {

    // Ensure param is a string to prevent unpredictable parsing results
    if (typeof arecode !== 'string') {
        console.log('Must pass the arecode as a string.');
        return;
    }

  

    // Ensure we don't parse strings starting with 0 as octal values
    const thisarea = parseInt(areacode, 10); 
    const country;
    const state;

    

    // Code blocks alphabetized by state
    if (thisarea == 205 || 938 || 251 || 334) {
        state = 'AL';
        }
    else if (thisarea == 907 || 250 ) {
        state = 'AK';
        }
    else if (thisarea == 480 || 602 || 520 || 928) {
        state = 'AZ';
        }
    else if (thisarea == 501 || 479 || 870) {
        state = 'AR';
        }
    else if (thisarea == 213 || 310 || 424 || 619 || 714 || 415 || 949 || 916 || 408 || 669 || 805 || 510 || 909 || 760 || 209 || 626 || 650 || 951 || 562 || 707 || 925 || 661 || 559 || 530 || 541 || 831 || 858 || 323) {
        state = 'CA';
        }
    else if (thisarea == 720 || 719 || 970) {
        state = 'CO';
        }
    else if (thisarea == 203 || 959) {
        state = 'CT';
        }
    else if (thisarea == 302) {
        state = 'DE';
        }
    else if (thisarea == 786 || 407 || 561 || 813 || 904 || 754 

Open in new window

0
Hi
I think I am ready to roll on my final proper game coding.

I can get html/javascript code running from my local OS X XAMPP  7.2 local server, of course, w MacBook IP address..but is isn't always-up, and I need it always on.

But, for an intended final product, I've been looking at the options for a real-world type dev system.

It looks like Amazon Web Services has very reasonable options for eventual monthly billing. here

I'll use the free tier.
For now, I need only the ability to put a simple page up that can load a device .io game in html and serve the game code to the player browser / device correctly.
Is that what gameLift is suited for? If I put my working .io game directory in my Godaddy space, it doesn't work. I apologize for bringing up Godaddy again. It'll be the last time, I hope. So, gamelift can serve an .htm that pulls up its .io code?
Is gamelift mainly for MMO games / games w player accounts?
I'd say that - My first game - .io game - is most similar to games like word-scapes and Drag-'n-Merge, not yet fortnite or Slither.io

Thanks
0
Do you see anything wrong in javascript part?

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <br />
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <h4 class="headline margin-top-0 margin-bottom-30">Tabs Style 2</h4>
            <div class="style-2">
                <!-- Tabs Navigation -->
                <ul class="tabs-nav">
                    @foreach (Domain.Event eItem in rv.EventTypeList())
                    {
                        if (eventCount == 0)
                        {
                            showActive = "Active";
                        }
                        <li class="@showActive"><a onclick="ShowSection('@eItem.EventType')"><i class="@eItem.EventIcon"></i> @eItem.EventType (@eItem.TotalCountEvent)</a></li>
                        eventCount = eventCount + 1;
                    }
                </ul>
                <!-- Tabs Content -->
                <div class="tabs-container" id="tabs-container" style="display:block;">
                    <div style="display:block;" class="tab-content">
                     <p id="tabs-data"></p>
                    </div>                    
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <br /><br />
        </div>
    </div>
</div> 
<script>
    function ShowSection(eventType)
    {
        alert(eventType);
        

Open in new window

0
hi experts

I am trying to update the version of my video player (ckplayer.com).
I have changed
line 7 and line 700 to 707 in here


But the player is not display.
Can you help me to check whats the problem?
Click here to see the original working video player.
0
I have written an autosuggest function in Javascript (plain javascript).

This autosuggest is a single box that searches a database table of about 3.5 million cities (including towns and villages) - the database actually also details region, and country but this isn't important.

Asking AJAX requests to search such a database takes many seconds per request and this is obviously too slow.

My immediate thoughts on how to speed this up as as follows:

Create separate database tables corresponding to each letter of the alphabet, i.e. 26 tables.

If the first letter the use types is 'a', consult the table with places beginning with 'a' from that point on.

In theory this would make the request 26 times faster?

My first question is:

Is the a sensible approach or am I missing something?

Furthermore, if that is still not fast enough,

take the table, for example all places beginning with 'a', and split that into a further 26 tables; i.e.

All places beginning with aa, ab, ac, ad........ az

My second question is:

Is this a sensible and logical approach? Is there a limit to the number of tables on can have in mysql (there would be 26x26 = 676 tables in this case)?


I am aware of indexing tables to speed them up, so the approach above would be 'on top of' indexing the tables.

I look forward to hearing from you.

thank you
James
0
Hi Experts,

I have the following code to avoid users entering "N/A" on a required field.

Now would like to add restriction of saving just space characters.

Thanks

$(":input[required]:visible").on("change", function() {
    var id = $(this).attr("id");
    var isName = id.indexOf("Last_Name")>0 || id.indexOf("First_Name")>0;
    var rgx =  isName ? /.*?N.*\/.*A/gi : /.*?N.*?A/gi;
    if($(this).val().length<6 && rgx.test($(this).val()) ) {
        $(this).val("");
        alert("N/A is not a valid input");
        var that = $(this);
        setTimeout(function(){
            that.focus();
        },350);
    }
});

Open in new window

0
I want to get a function on my form, which will automatically get the users's state based on the phone number entered.
- A user, will enter their phone number with area code in the phone field. from that, it use a function, to determine the State, and pass that state as a value through a hidden field in the form.

I've got a function getState(areacode) which will do this, but i'm unsure on how to put it all together.

Here's what i have so far.

Form Code
<div class="rounded-lp-form">
	<div class="lp-form-header">
		<h1 style="text-align: center;">Get started <br/> risk free.</h1>
		<p style="text-align: center;"><span class="text-black">Already an existing customer?</span>
			<a href="/company/contact-us/">Contact us here.</a>
		</p>
	</div>

<form id="testing-lp-form" class="" action="xxxxxx" method="get">

<div>
    <input type="text" id="full_name" name="full_name" required placeholder="Full Name" />
    <label for="full_name" class="hide-label">Full Name</label>
 </div>
  
  <div>
    <input type="email" id="email" name="email" required placeholder="Email Address" />
    <label for="email" class="hide-label">Email Address</label>
  </div>
  
<div>
	<input name="phone" id="phone" type="tel" placeholder="Phone Number" required>
	<label for="phone" class="hide-label">Phone*</label>
</div>
  
  <input type="hidden" name="code" value="3Q3X7">
  <input type="hidden" name="autoCode" value="true">
  <input type="hidden" name="name" value="" 

Open in new window

0
If I change my style sheet (.css file) I want to force a reload of the file. What is the best way to do this? Is it by adding a query string? Ie:
<link href="style.css?ver=2" rel="stylesheet">

and then changing ver= each time my style sheet changes?

Should I do the same thing for js files?
0
hi am having this error in my angular application
Uncaught Error: Template parse errors:
Can't bind to 'posts' since it isn't a known property of 'app-post-list'.
1. If 'app-post-list' is an Angular component and it has 'posts' input, then verify that it is part of this module.
2. If 'app-post-list' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("n>
<app-post-create (postCreated)="onPostAdded($event)"></app-post-create>
<app-post-list [ERROR ->][posts]="storedPosts"></app-post-list>
</main>

"): ng:///AppModule/AppComponent.html@4:19
at syntaxError (compiler.js:2175)
at TemplateParser.parse (compiler.js:11292)
at JitCompiler._parseTemplate (compiler.js:25837)
at JitCompiler._compileTemplate (compiler.js:25825)
at compiler.js:25769
at Set.forEach (<anonymous>)
at JitCompiler._compileComponents (compiler.js:25769)
at compiler.js:25682
at Object.then (compiler.js:2166)
at JitCompiler._compileModuleAndComponents (compiler.js:25681)
syntaxError @ compiler.js:2175
parse @ compiler.js:11292
_parseTemplate @ compiler.js:25837
_compileTemplate @ compiler.js:25825
(anonymous) @ compiler.js:25769
_compileComponents @ compiler.js:25769
(anonymous) @ compiler.js:25682
then @ compiler.js:2166
_compileModuleAndComponents @ compiler.js:25681
compileModuleAsync @ compiler.js:25643
0
I'm writing an auto-complete script little by little (html/ plain javascript/ php/ ajax).

I've come across the following code:

var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");

Open in new window


... and would like to understand this particular bit of the above code

What does the following bit mean? I've never seen logic like this before.

if (x) x  =  


Is this a comparison / some kind of logical operator? I'm wondering if it's a way to detect whether x is NULL and so get information from the immediate parent element. Nevertheless, I'd like to understand what it means.

If so, in 'long English', what does it mean?

Thank you
0
Im noob in node.js and my clients program is generating a build file from the code. But i dont know how this works! Im in a crunch for time on the clock. Can someone explain how this is being generated?  The program works off the generated Build File and not my code. Thank you.

Node.js build file auto generated.
0
Hi,

I am working on ASP.Net using C#

In my aspx file, I need to pass variable in string to javascript variable

<head>
 <%
        string isUserLoggedIn = "0";

        if (HttpContext.Current.Session["MEMBER"] != null)
        {
            isUserLoggedIn = "1";
        }

        string strRetURL = Common.getMemGuid();
    %>

</head>
<body>   
    <script>
        var retUrl = "@strRetURL";
        alert(retUrl);
    </script>

Open in new window


The variable is not printing but it is printing alert as @strRetURL

The name 'strRetURL' does not exists in current context.

Please advise the solution.
0
Generally, my thinking is to (1) create two files reCaptcha-test.html and reCaptcha-test.php; (2) prevent.default on the form's submit button, (2) use jQuery submit function to redirect the post to reCaptcha-php for processing. (3) if processing is successful, restore the original form processing, client verification and post to sendForm.php. If reCaptcha processing fails, viewer is referred to a custom error page, failure.htm.

My code is below. It does fetch the reCaptcha token, but my minuscule PHP skills fail after that.  I'm hoping someone can help debug this and point me  in the right direction.

reCaptcha-test.htm

<!doctype html>
<html lang="en" class="no-js">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <title>"reCaptcha v3 Test"</title>

    <script src='https://www.google.com/recaptcha/api.js?render=SITE-KEY-GOES-HERE'></script>
    <script src="./_js/vendor/modernizr/modernizr-custom.js"></script> 

    <link rel="apple-touch-icon" href="./icon.png">
    <link rel="stylesheet" href="./_css/main.css" crossorigin="anonymous">
  </head>

  <body>
   
  
          <div class="c-contact-block-2__form-wrapper">
            <form class="needs-validation form-box" novalidate method="post" action="http://www.themagnolia.com/sendForm.php" name="contactForm" id="contactForm">
            <input type="hidden" name="env_report" 

Open in new window

0
I have this code for a Wheel spinner using html, css and javascript.  At the moment, the only way I can get it to re-spin is to use the refresh button.  How can I add a button to re-spin the wheel?

I've tried adding a spin event and having the button call the spin event, but it fails even when the spin event just call init().
Here is the unminified javascript for SpinningWheelSource.js https://unpkg.com/konva@4.0.0/konva.js

<!DOCTYPE html>
<html>
  <head>
    <script src="SpinningWheelSource.js"></script>
    <meta charset="utf-8" />
    <title>Konva Wheel of Fortune Demo</title>
    
    <link rel="stylesheet" type="text/css" href="SpinningWheelStyle.css">
    
  </head>

  <body>
  <!--<button onclick="spin()">Spin</button>-->
  
    <div id="container"></div>
	
    <script>
	  //var myDiv=document.getElementById("container");
	  //var myParent=mydiv.parent;
      var width = window.innerWidth;
      var height = window.innerHeight;
      
      Konva.angleDeg = false;
      var angularVelocity = 6;
      var angularVelocities = [];
      var lastRotation = 0;
      var controlled = false;
      var numWedges = 10;  //not 25
      var angularFriction = 0.2;
      var target, activeWedge, stage, layer, wheel, pointer;
      var finished = false;
        var randy=Math.random();
		//alert("Random Number ="+randy)
		var Duration
		if (randy<0.1)
		    Duration =600;
		else if (randy<0.2)
		    Duration =650;
		else if (randy<0.3)
		    Duration =700;
		else if 

Open in new window

0
I am using Kintone  JSedit (Java Script)? I am working on a basic application but my native language is not Java so I'm really at a disadvantage here and resources are thin.

I need to calculate a total using data entered in my form.  

Tyler
0
I have this datatable but it goes under my footer. Does anyone have a fix? margin or padding dont seem to work.
table-mobile.PNG
0
popup that is currently renderedI have the following popup that needs to be changed to better align with UI standards.

This is the AngularJS that makes this page:

I need to put some padding , alighn the buttons properly.  Can someone help me refactor?




<script type="text/ng-template" id="ApproveArRequestTemplate.html">
    <form>
        @*<div class="modal-header">
            <h3 class="modal-title">Add attachment</h3>
        </div>*@
        <div class="modal-body">
            <div class="control-group">
                <label class="control-lable">Approval Comment</label>
                <div class="controls">
                    <textarea id="approvereason" name="approvereason" class="form-control" ng-model="ApproveReason"></textarea>
                </div>
            </div>
            <div class="checkbox" ng-show="item.IsRoleEvpCfoCoo">
                <label><input type="checkbox" id="IsRouteToCEO" ng-disabled="IsRouteToCEO" ng-model="IsRouteToCEO" />  Route to CEO for approval</label>
            </div>
            <div class="checkbox" ng-show="item.IsRoleCreditDeptFPnACommOp">
                <label><input type="checkbox" id="IsRouteToDirectorOfTax" ng-model="IsRouteToDirectorOfTax" />  Route to Corporate Tax</label>
            </div>
            <label class="control-label" ng-show="item.IsRoleLocalFinance">Are Pre-Approved Business Metrics Met</label>
            <div class="col-md-6">

                <div class="btn-group" 

Open in new window

0
Hi Experts

Could you point how to adjust this PHP/ Bootstrap code to repeat 02 times the same box at the right part the same way it is at the left part?


Accordingly with these pictures:

img004
To:
img006
The code actually in use:
<section class='row'>
	<div class="col-md-12 titulo">Vídeos</div>
    <div class="col-md-12 text-center">
        <a href="/videos">
            <img src="{{ asset('img/img_thumb_video_gadget.jpg') }}" />
        </a>
    </div>
    <div class="col-md-12" style="padding-top: 9px;">
        <a href="/videos">
            ver todos os vídeosXX
        </a>
    </div>

	<script src="{{ asset('js/.../xxx.Noticia.js').'?v='.....) }}" ></script>
<section>

Open in new window


Thanks in advance.
0
I wanna use a bootstrap data table but i cant get it to work.
this it the code in my header:
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
    <script type="text/javascript"  src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>>

Open in new window


What line do i need to add to get bootstarp datatable since the one i have been using does not seem to work.
0
Maybe a stupid question - but I'm not a front-end guy, and my new front-end developer won't start for a couple of months.

I'm working on a solution for a microservices based data tool. Simply, this will be an interactive dashboard where users can add selected interactive widgets, from which they can select data to have a chart drawn. Sometimes the data needs to be sent directly from one widget to another widget - and sometimes an external microservice will need to do processing on the data before a new chart is drawn.

Based on this, I came up with the following schema (see image). I believe it makes sense to have the dashboard's API accept data from the external microservice, and then generate the interactive graph widget.

What I'm unsure of is; does it make sense to have the dashboard call it's own API for one widget to create another widget.

When I coded with Node.js, we did this all the time - but only with data and only in the backend (where one Node.js service just called another Node.js service - and they would talk back and forth via their APIs.)

Does this continue to make sense for a graphing frontend?

selfcallingapispng.png
0
Hey i have this table in html which is scrollable vertically. This works but there is an issue the headers do not allign with the text in the table. Does anyone know how i can fix this?
this is the code:
table {
  display: inline-grid;
  grid-template-areas:
  "scrollable";
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}


tbody {
  overflow: auto;
  height: 400px; /* define height depending on your needs */
  width: 100%;
}

Open in new window


And the table is:
   <table>
        <thead>
            <th>Username</th>
            <th>Result</th>
            <th>Quiz name</th>
            <th>Category</th>
            <th>Date</th>
        </thead>
        <tbody>
            {% for res in result_sql %}
            <tr>
                <td>{{res.username}}</td>
                <td>{{res.result}}</td>
                <td>{{res.quiz_name}}</td>
                <td>{{res.category}}</td>
                <td>{{res.date}}</td>
            </tr>
            {% endfor %}

        </tbody>


    </table>

Open in new window


I will also attach a photo of the table if anyone could help that would be great!
table.PNG
0

JavaScript

123K

Solutions

42K

Contributors

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and  in almost every mainstream web browser.