JavaScript

122K

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.

Share tech news, updates, or what's on your mind.

Sign up to Post

I'm using Angular and Typescript/Javascript.

I am getting an error message that says, "this is undefined." With this code:

public converse(msg: string) {
    const userMessage = new Message(msg, ESendBy.user);
    this.update(userMessage);

    return this.client.textRequest(msg)
      .then(res => {
        console.log(res);
        const msgArr = res.result.fulfillment.messages;
        if (Array.isArray(msgArr)) {
            console.log("in array");
            console.log(msgArr);
            msgArr.forEach(function(entry) {
              const botMessage = new Message(entry.speech, ESendBy.bot);
              console.log(botMessage);
              this.update(botMessage);
            });
          }
        else {
          console.log("not array");
          const speech = res.result.fulfillment.speech; 
          const botMessage = new Message(speech, ESendBy.bot);
          this.update(botMessage);
        }
      });
  }

Open in new window


When the variable msgArr is NOT and array, the this works.

But when the variable msgArr IS an array, it gives the above error.

Here is what is being returned from the text request:

fulfillment: Object { 
speech: "If you know nothing about MYLC, please ask for an overview.", 
messages: (2) […]
​​​​0: Object { type: 0, speech: "Hello. If you are here to learn about a theme, please state the theme name." }​
1: Object { type: 0, speech: "If you know nothing about MYLC, please ask for an overview." }​​​​
length: 2
messages: (2) […] }

Open in new window

0
Big Business Goals? Which KPIs Will Help You
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

try to reload the page after a success message, but it is not reloading..

i have this code

$.ajax({
				type:"post",
				url: '/action.cfm?method=quote',
				data: datastring,
				success: function(data) {
					var valid = $.trim(data);
					if(valid.toLowerCase().indexOf("error") == '-1') {
						localStorage.setItem("swal",swal({title:"Good job!", text:'Thanks',
						type:"success",showConfirmButton: true}).then(function(){
						location.reload();
						})
						);
						localStorage.getItem("swal");
					}else {
						swal("Oops",data,"error");
					}
				}
			});

Open in new window

0
The following code contains an embed tag.  However do I dynamically insert the embed tag?

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="ViewPDF.aspx.vb" Inherits="ViewPDF" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script>
        $(function () {
        });

        function Test() {
            //Insert <embed> tag
            alert(hfPDFViewer.Get("PDFName"));
        }
    </script>
</head>

<body id="Main" onload="Test();">
    <form id="form1" runat="server">
        <%--<embed id="PDF" src="" type="application/pdf" />--%>
        <dx:ASPxHiddenField ID="hfPDFViewer" runat="server" ClientInstanceName="hfPDFViewer">
        </dx:ASPxHiddenField>
    </form>
</body>
</html>
1
Dear experts,

I came across this issue when declaring the <canvas></canvas>  in the <body> tag. I want the canvas to be as big as my browser. I assigned an id to my canvas as 'myCanvas' and applied these code in javascript:

var myCanv = document.getElementById('myCanvas');
myCanv.width = window.innerWidth;
myCanv.height = window.innerHeight;

for my html code it looks like this:

<!DOCTYPE html>
<head>
    <meta>....
<link rel="stylesheet" href="../canvas.css"/>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script src="../canvas.js></script>
</body>

I see the horizontal and vertical scroll bars. I wonder why am I getting the scroll bar which I haven't include anything into my canvas and my canvas has the same size as the window inner width and height.

I've also tried document.body.scrollWidth, body.clientWidth, $(window).width(), and document.documentElement.clientWidth. ( I can see some of those have different outputs but I can't get rid of the scroll bars).

I've also tried swapping <canvas> with <div> which the <div> doesn't show the scroll bars.

Is there a way for me to declare canvas the same size as my browser display without showing the X and Y scrollbars? Thanks
0
I have this Javascript which is invoked when a submit button is pressed.

The form statement is <form method="post" name="st" action="save_sess_cust.php" onSubmit="return chk_vals();">

The javascript code is as follows (ac = "go");

if (ac == "go") {
			alert("go to ac = go");
			alert("group = " + group);
			if (group == "sand") {
				if (document.st.voltage.value == "") {
					alert("Voltage required.");
					return false;
				}	
				document.st.action = "opts_ref21.php?voltage=" + document.st.voltage.value;
				return true;
			}
			alert("cltype = " + cltype);	
			if (cltype == "F") {
				document.st.action = "options.php?fr=cust";
				return true;
			}
			alert("ssmed = " + ssmed);
			if (ssmed == "") {
				if (document.st.voltage.value == "") {
					alert("Voltage required.");
					return false;
				}	
			}	
			document.st.action = "options.php?fr=cust&ssmed=" + ssmed;
			return true;
		}	

Open in new window


This javascript is a part of chk_vals() function.

The last alert it displays is cltype = S. Since cltype is NOT F, how can it skip the last alert?

Furthermore, it seems to me that in exiting this Javascript, it MUST go to options.php. I put a small bit of code in options.php None of that code is executed, I cannot see how it goes to another php program.

I'm stumped. Can someone help?

Thanks
0
The slide anchor works well in full screen, however, it does in mobile.  In the mobile if I click on "Announcements" on the top expandable menu it works.  If I click on "Coverage" it slides down, but the menu disappears.  I thought that perhaps the main picture image was getting in the way so I moved the anchor down, but the menu lines didn't show up.  In other words, the menu bar is there for "Announcements".  It is not there for Coverage.  For some reason the menu disappears on coverage.

http://insuranceqa.illinois.gov/HeyCMS_StayOutOfMyFilesPlease!/GCI2/index.html
0
I used to use a lot of JQUERY AJAX calls in our code, but recently I have been moving to using modern plain Javascript, such as fetch and promises.

A typical API block would look something like this:
$.ajax({
     url: '/piece.json',
     type: "GET",
     dataType: "json",
     success: function (data) {
         alert(data);
     }
});

Open in new window


I want to start writing my API calls using Promises, but I am a little confused, especially when it comes to chaining and error checking.

Could someone show me an example using chained promises that does the following psuedocode?

Example Login Functionality
let username = "john";
let password = "123";

if username doesn't exist
-- doesn't exits
     show message, return false
-- it exists
     check password. Is it correct?
     -- No
         Show error message, return
    -- Yes
         send then on their way to dashboard or something

Open in new window


So I know the basics of Promises, but when it comes to chaining something like that...

I know how to check them individually ( I think I am doing it correctly anyways ):

let getUserName = function(email){
    return new Promise(function(resolve, reject){
        // Apply any logic here, call our API
       //  Mock response
        if(email == "john@gmail.com"){
            resolve("found");
        }

        reject("Not found!");
    });
}

Open in new window


Then I could use my Promise like this, right?

getUserName("john@gmail.com").then((response) => {
    alert("Your username was: " + response);
    }, (e) => {
        // Handle error if we want to. BUT what error???
    alert("Error: " + e);
});

Open in new window


So even here, I am unsure of what error I am trapping. Am I just catching the reject here? Anyways...

Let's say I want to use that Promise, or something similar, but chain it as I described above. How?

Can someone help me with an example of a Promise based login using my psuedocode example code, to help me get going? Seeing it sure would help I think.

Thanks!

John
0
Hello,
Need advise on writing the  an algorithm for the spec below:
Return 3 digit integer as day month year by adding  an number to a given date
Example date given is 1-1-2019 and integer to be added is 40 . Also just need the logic without any built in functions.
Any suggestions?
Thanks
0
I have a simple web application (on a remotely hosted server) which has my pizza menu on and I can place orders, etc.

The webpage is built on php/mysql and using some javascript to provide quicker data for my customers (example further below)

Now the issue I'm faced with is I have to type phone numbers to find customers.

How can I go about getting the client side modem to detect the caller ID number and pass it to the webpage?

I appreciate that php can't help me here but I mention that to help understand the position I am in.

I have searched the internet for help to my problem but am left scratching my head, TAPI should help somewhere but as I am not familiar with C++ I'm left unsure where to start.

I've been suggested looking at nodejs but I'm finding that a lot easier said than done.

<script>
function autocomplete(inp, arr) {
  /*the autocomplete function takes two arguments,
  the text field element and an array of possible autocompleted values:*/
  var currentFocus;
      /*execute a function when someone writes in the text field:*/
  inp.addEventListener("input", function(e) {
      var a, b, i, val = this.value;
      /*close any already open lists of autocompleted values*/
      closeAllLists();
      if (!val) { return false;}
      currentFocus = -1;
      /*create a DIV element that will contain the items (values):*/
      a = document.createElement("DIV");
      a.setAttribute("id", this.id + "autocomplete-list");
      

Open in new window

0
We are constantly re using very similar code blocks when it comes to describing the API for the project we are working on.

I would like to describe our API's for all our projects using JSON. I am not good, however, at structuring well formed JSON.

We would need the following data:

1. Internal company name [ we have 2 ]
2. The project name
3. Client Info ( name, address, etc )
4. Project Info ( url, description, notes )
5. Api info
     -- base url ( each project has one directory )
     -- endpoint url ( /getUsers )
     -- endpoint friendly name ( Get Users )
     -- endpoint method ( post )
     -- endpoint parameter type ( body, path, queryString )
     -- endpoint parameters
           name, type

I guess that would be it. I just want a catch all JSON that we can use to for an admin site we are making for the company, as well as to call upon for our projects.

Can anyone help me get going?

Thanks!
1
Determine the Perfect Price for Your IT Services
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

We want to introduce a Loyalty / Referral feature to our site.

-- A user can enter a referral code on their checkout form to receive a discount
-- The person who referred them will be rewarded, at this time simply by points incremented.
-- A user can refer someone and a code is generated that is associated with them
-- A code can only be used once
-- A user can only refer XX amount of people.

That being said, we are using JavaScript to code this with.

I have been tasked with this, and the boss wants this done in some sort of OOP / MVVM pattern. The reason I am highlighting this fact is because they know my coding skills are mid level at best.

Ideally, I know my end result should look something like this:
let referral = {
 
   generateNewCode: function(){

   },

    getNumberOfReferralsByUserId: function(id){

     },

     codeHasBeenUsed: function(code){
          return true;
     }

}

Open in new window


That is how I would approach this I guess. I COULD try TypeScript if a class would be better, but new to that.

Can someone show me the best way to approach this using pure JS? The code will not do anything more than I described.

There will be API endpoints to actually hit the data.

I would really love to see some clean, modern approach to a simple function group like this. For instance, getting and setting should be a global function, right??? IDK...

Help!

Thanks!
0
I have a products and category collection. I want to query both of them and send the data through one controller so I can display products and categories in the same view.

This seems to work but I am not sure if it is the correct way of doing it? If not, please could you you advise me on a more appropriate way.

exports.getIndex = (req, res, next) => {
  Product.find({ status: "approved" })
    .sort({ createdAt: -1 })
    .then(products => {
      Category.find({})
        .sort({ catName: 1 })
        .then(category => {
          res.render("shop/index", {
            pageTitle: "My home page",
            path: "/",
            prods: products,
            category: category
          });
        });
    })
    .catch(err => {
      console.log(err);
    });
};

Open in new window

0
I am using the select2 drop down list for states. The problem I have is that when you tab over to it, it doesn't allow you to type in a letter to go straight to the state in the list. Yes, you can hit Enter to open it up, but I'd like it to work as the select normally does by default.

Here is my code:

$('.ddlState').select2({
placeholder: '[Select]',
matcher: function (params, data) {
    return matchStart(params, data);
    },
width: 'resolve',
selectOnClose: true
});

Open in new window


I have checked their examples to see if it's possible and find one here under Multi-select boxes (pillbox). but I'm thinking maybe that's only if I change it to multiple, which I do not want. I viewed source code and see nothing in there that would indicate an option to hot key. Don't be fooled by the first example on their page, that's what the select box looks like by default before they turn it into a select2 box.
https://select2.org/getting-started/basic-usage

It appears this just doesn't have that ability, which is too bad if it doesn't, because that makes it unusable.

If you know of a way, please share!

thanks!
0
I am trying to utilize this piece of classic asp code and am getting errors:
<a href='javascript:delay(Update.asp?c=" & request.QueryString("c") & "&g=" & request.QueryString("g") & "')>

Open in new window

I only get errors when request.QueryString("g") contains a space:

Invalid left-hand side in assignment

Below is the function:
<script>
	function delay (URL) {
	setTimeout( function() { window.location = URL }, 500 );
	}
</script>

Open in new window


Thoughts?
0
I have the code where i want to return the true/false and because i am using that function somewhere else to see if i get false, do this else do nothing

this is my code and it is giving me callback is not defined

function CheckIfPaused(callback) {
	$.post('/cfc/cfc.cfc?method=check',{id: $('body').attr('data-id')}, function(data) {
		if(data.status == 1) {
			callback('true');
		}else {
			callback('false');
		}	
	},'json');
}

Open in new window


$document.ready(function() {
if(CheckIfPaused() == false) {
do this 
}
});

Open in new window

1
Somebody has a good example autocomplete search nodejs, express, mongodb
0
Hello this is my cod  for a test page

<script language="javascript" type="text/javascript">

	$(document).ready(function() {
		inLoop()
		
		/*var suport_fileReader;
		try { suport_fileReader = (window.FileReader) ? true : false }
		catch(e) {}
		document.getElementById("windowFileReader").innerHTML = suport_fileReader;
		document.getElementById("modernizrDragnDrop").innerHTML = Modernizr.draganddrop; */
		secFunc()
	});
	
	
	async function inLoop() {
	 var startTime = Date.now();
	 while ((Date.now() - startTime) < 3000) {
	  console.log("In Loop ", (Date.now() - startTime) )
	 }
	 alert(1)
	}
	
	function secFunc(){
	
	alert(2)
	}
</script>
<body>
<h1>Tests</h1>

Open in new window



1) I am expected that alert 2 will come before the alert 1 because the async  -
2) on IE11 async function inLoop() get error

I have long script that give a not responding for some time  i thought to use async   that the problematic function will run on the background - this is possible?
0
How do I determine if a script is a manifest script?  I need to list them all for a specific web app. I can obviously filter ".json" files  but how will I know if it is a manifest script?

Thanks!
0
Hi,

I have a requirement.I need to write in HTML/ JavaScript / CSS to embed a  chat BOT widget (web chat window) on an ASP.NET website with collapsible window. Initially an icon should be shown  and on click of that icon it should play an audio sound and then display that collapsible pop up .
(i.e.,The popup widget  should stick to the bottom of the browser and popup /collapse feature.)
An help will be highly appreciated.
0
Introduction to Web Design
LVL 12
Introduction to Web Design

Develop a strong foundation and understanding of web design by learning HTML, CSS, and additional tools to help you develop your own website.

I am using DropZone but would like to send another form field to my controller.  I don't think I can add the form field inside the Form - other than as a hidden field.
I have my View as:

    @{
        ViewBag.menu = false;
        ViewBag.Title = "Upload New ARC Request";
        ViewBag.maxFiles = 1;
    }

<div class="col-xs-10">

        <div class="row">
            <div class="col-xs-6">
                @Html.Label("Title:")
                @Html.TextBox("NewTitle", null, new
           {
               @class = "form-control",
               @placeholder = "Enter Title",
               @id = "NewTitle"
           })
            </div>
          </div>

            <div class="row">
                @using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new
                {
                    @class = "dropzone dz-clickable",
                    @enctype = "multipart/form-data",
                    @id = "documentDropzone"
                }))
                {
                   @Html.Hidden("title", t)
                        <div class="dz-message">
                            Drop files here or click to upload.
                        </div>
                }
            </div>
            <script type="text/javascript">
                Dropzone.options["documentDropzone"] = {
                    maxFilesize: 10000,
                    acceptedFiles: "application/pdf"
                };
            </script>
        </div>

</div>

<script 

Open in new window

1
I have a javascript button at https://www.theherbsplace.com/rebate-program/ it is found at the bottom of the page. The button state is being carried over to every customer.  I need to make sure if someone doesn't want membership that the message doesn't show up that they do.

This is a WooCommerce site.

Here is the code

<script>
document.getElementById("order_comments").innerHTML = "I want membership";
</script>

Open in new window


<p><a class="button exclusive biz-op-button" title="I Want Membership!" href="#" data-register="true">Get My Membership</a></p>
<p class="form-row notes" id="order_comments" data-priority="">
    <label for="order_comments" class="">Order notes&nbsp;<span class="optional">(optional)</span></label>
    <span class="woocommerce-input-wrapper">
        <textarea name="order_comments" class="input-text " id="order_comments" placeholder="Notes about your order, e.g. special notes for delivery." rows="2" cols="5"></textarea>
    </span>
</p>

Open in new window

0
Dynamics 365 8.2.3,

We are running Dynamics 365 8.2  and having an issue with editable grids.  When using the editable grid, XRM.Page is not supported so code to summarize grid data and update a field on the parent form only works when the form is Refreshed, not when the value is edited “in-line”.

I can make this work, but I need to to capture the grid column value, when changed on the “onchange” event.

According to the documentation I have found, the code examples seem to utilize Dynamics 365.  I’m not sure the Javascript we have supports the examples I have seeing online…specifically the “getFormContext”

Please review the code below and let me know what I need to change.

Thanks

function pvalue(context) { 
    alert("here");  //this works
 
    var estimatedvalue = context.getFormContext().data.entity  // this does not
    var val = estimatedvalue.attribute.getByName("ring_estimatedvolume");
    alert(val.getValue()); 
}
 

Open in new window

0
Hi, Please see http://dev.magickitchen.com/weight-loss-meal-delivery/  - I don't think you'll need to log in.

I have an earlier question, https://www.experts-exchange.com/questions/29132073/White-space-on-scroll.html  in which I got a lot of help, but now I have a javascript related question that sparing from that.

Scott said to remove the headroom plugin after fixing the code errors. I made the change on the last line, and now the errors are gone (thanks, Scott!).

But now when I try to remove the headroom section, I get a syntax error. I am trying to remove this exact code:
      function Headroom (elem, options) {
        options = extend(options, Headroom.options);

        this.lastKnownScrollY = 0;
        this.elem             = elem;
        this.tolerance        = normalizeTolerance(options.tolerance);
        this.classes          = options.classes;
        this.offset           = options.offset;
        this.scroller         = options.scroller;
        this.initialised      = false;
        this.onPin            = options.onPin;
        this.onUnpin          = options.onUnpin;
        this.onTop            = options.onTop;
        this.onNotTop         = options.onNotTop;
        this.onBottom         = options.onBottom;
        this.onNotBottom      = options.onNotBottom;
      }
      Headroom.prototype = {
        constructor : Headroom,

        /**
         * Initialises the widget
         */
        init : function() {
          

Open in new window

0
Hi

In  my ASP.net web app I am using the following Javascript code to redirect users on mobile devices to another page.
On a different page I want to hide a Menu bar called "Menu1" and show a hyperlink called "Link1"

How would I do that?

<head runat="server">

    <script type="text/javascript">
    <!--
    if (screen.width <= 699) {
    document.location = "http://steel1.azurewebsites.net/Mobile_OffersByMe";
    }
    //-->
    </script> 

</head>

Open in new window

1
how to show java-script alerts and HTML dialog input in Xamarin crosswalk ????
its working by default when using crosswalk in android studio ..
1

JavaScript

122K

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.