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 Team,



I have an issue with date time picker. i have 3 date fields that are Pdate,Qdate,bDate , i put the validation while selecting B Date is greater then Q Date and q Date is greater then P Date and B Date is greater then P Date simple you can say that P Date , Q Date and B Date is in increasing order when i am taking date picker it's working fine but when i am using the date time picker its comparing each column time separatly and checking the time also in increasing order but i want only date compare my code is below please check and let me know if you need more clarification . please help me out on my below code where
i m doing wrong.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.min.js"></script>



<script>
    function validateDates() {
	 //get values of dates
	 var array = [];
	 var error = false;
	 $(".chkValues:checked").each(function() {
	   var parent = $(this).closest('tr');
	   var last = 0;
	   //var lbl = 

Open in new window

0
Hi everybody.
So I have the website1.com which links some resources from the website2.com/static (both have SSL active): resources are images, css, javascript and fonts. All resources are correctly loaded but fonts. For fonts I get a CORS issue:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.webintenerife.com/static/fonts/Chandstate.otf. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

downloadable font: download failed (font-family: "ChandState" style:normal weight:400 stretch:100 src index:0): bad URI or cross-site access not allowed source: https://www.website2.com/static/fonts/Chandstate.otf

Open in new window


I have set the header in my .htaccess both in website2.com/static and in website2.com:

<FilesMatch "\.(ttf|otf|eot|woff|woff2)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "https://website1.com"
  </IfModule>
</FilesMatch>

Open in new window


Any idea?
Thank you in advance
0
What would be the Javascript code to attach and event listener to this element?
<button type="button" class="btn btn-mobile btn-tertiary btn-grp-back mt-5" data-name="btn-grp-back">Back</button>

Open in new window

Here is a bigger picture of the structure.  larger view of element structure
Thanks!
0
I am calling a Flask API from React (both running on localhost) and I am running into CORS problems. When the request is made, the browser (Chrome) gives the following error

Access to XMLHttpRequest at 'http://localhost:5000/sas' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

Open in new window


Setup

The Flask setup is the following

from flask_cors import CORS
from flask import Flask, request, Response
from flask_restful import Api, Resource
import json

class SAS(Resource):
    def get(self):
        content = request.json
        js = json.dumps(
            {
                "Response": "Some response"
            }
        )
        resp = Response(js, status=200, mimetype='application/json')
        return resp

app = Flask(__name__)
cors = CORS(app)
api = Api(app)
api.add_resource(SAS, '/sas/')

Open in new window


The call using axios in React is the following

  buttonPressed = async event => {
    event.preventDefault();
    const response = await axios.get(`http://localhost:5000/sas`, {
      data: {
        user: "user",
        file_name: "user",
        directory_name: "user"
      }
    });
  };

Open in new window


NOTE: Running the request from Postman works and shows the header Access-Control-Allow-Origin = *

Any idea on how to solve the problem?

Also, if I was to run the React frontend and API as a dockerized application, I should not see this problem anymore correct?

In this case I would also consider circumnavigating the problem while I am developing
0
I've got a form that looks like this:

<form id="user-form" class="needs-validation" method="post" action="/profile/save" novalidate>

...

      <div class="password-wrapper">
        <button type="button" class="btn btn-primary btn-change-password"><i class="fas fa-fw fa-key"></i> Change Password</button>
        <div class="password-template d-none">
			<div class="row">
				<div class="col-lg-12">
				To change your password, begin by entering your current password first...<br><br>
					<div class="md-form">
						<input type="password" id="current-password" name="current_password" class="form-control" value="">
						<label for="current_password"><a id="expose-current" href="#" style="cursor:text;" tabindex="-1">Current Password</a></label>
					</div>
				</div>
			</div>
			<!-- new row -->
			<div class="row">
				<div class="col-lg-6" style="margin-top:-25px;">
					<div class="md-form">              
						<input type="password" id="user-password" name="user[password]" class="form-control" required />
						<label for="user-password"><a id="exposure" href="#" style="cursor:text;" tabindex="-1">Password*</a></label>
					</div>
				</div>
				<div class="col-lg-6" style="margin-top:-25px;">
					<div class="md-form">
						<input type="password" id="user-confirm" class="form-control" required />
						<label for="user-password">Confirm*</label>
					</div>
				</div>
			</div>
			<div class="row">
				<div class="col-lg-12">
					<div style="font-size:9pt; 

Open in new window

0
Sorry for the newb sounding question.

I am starting a project in with AWS and I am trying to find a CDN location for the AWS Cognito js files.

I have looked all over the AWS documents for Cognito and was not able to find the information that I need.

Not for sure if I am asking the right questions.  I just want to be able to pull the js files without having to put them on my server.

Thank you
0
Here is the current live version of the page I want to change.

http://www.fobgfc.org/?page=team&side=1&season=2019

When viewed on a phone the fixtures CSS shows them like image01.

mobile emulator of current live version.
My problem is that each fixture takes up too much space.  So for narrow widths (<600px) I have changed the PHP/HTML and CSS via media queries to show only Date, Opposition and Competition so it all fits on one line.  This is image02 from my test site http://www.col-b.uk/?page=team&side=1&season=2019

phone emulation image from my test site
So far so good.

The end goal is to toggle each fixture to show a popup with the detail of scores etc.  What is the easiest way to do this?  JQuery toggle or javascript alert box? Or another way?

In either case do I need a separate button to tap to toggle, or can I use the fixture row itself?

All help appreciated.

PS I still don't know how to preview a question before asking it, so hope this turns out well!
0
Hello,

I am using a drop down list function which loads data when a select menu changes.. this works fine.
$("[name=shipbook_to]").change(function(){

I also have another function which applies the  jquery  ui.combobox to my selects (this you can see working in JS Fiddle)

These work great separately, but not if I combine them.. the .change(function() does not trigger if the select option is chosen through ui.combobox


I created a JS fiddle so you can see it in action
https://jsfiddle.net/justindark/b7c12ehv/34/

This part is not happening when I select the Delivery address..  But if I remove the UI combobox, it works perfectly

$(document).ready(function(){		   
					$("[name=shipbook_to]").change(function(){
						var form_data_cc = $("[name=shipbook_from]").val();
						var form_data_dd = $("[name=shipbook_to]").val();
						$("[name=shipbook_from]").attr("value", form_data_dd);
						$("[name=shipbook_to]").attr("value", form_data_cc);
						$('[name=broker]').load("includes/ship_to.php?from="+form_data_dd+"&to="+form_data_cc);
            // THIS JUST LOADS ANOTHER SELECT MENU, WORKS WTHOUT COMBOBOX
                                                 alert("We did something!");
						
						});
					});

Open in new window

0
I'm following the instructions here
The text is fixed in the example.
How do I vary the text at runtime.

In my code I need the text to vary depending on the day of the month.
0
I'm new to Nodejs and I'm working on a ticket where I'm being tasked with first checking the user's current password before they're allowed to change it.

Here's the current route:

router.post('/profile/save', async (req, res) => {
  try {
    if (typeof req.body.user == 'undefined') {
      return res.send(user.error('Invalid request.'));
      }
          
      //checking to ensure current password matches what's in the database before updating profile information
      
      let check = await(user.getOne(global._user._id // here's where I get stuck
      
    let resp = await user.save(global._user._id, req.body.user);
    if (resp.error) {
      return res.send(resp);
    }

  #1) let data = await user.getOne( global._user._id, [
      { path: 'account', model: 'Account'}
    ] );

    req.session.user = Object.assign({}, req.session.user, data);

    flash.add(req, 'Your profile has been successfully saved.', 'success');

    res.send(resp);
  } catch (err) {
    res.status(500).send(User.error());
  }
});

You can see where I've notated "here's where I get stuck," but I've got an idea of what the flow needs to look like.

I need to first find the row that coincides with the global user_id. After I get that array, I need to parse it out and decrypt the password as it exists in the database and compare that to what the user entered in the "current password" field.

One other thing: #1 - what is user.getOne? I've seen "findOne," but can't …
0
Hi all,
I am asking for your help on a small project that I am implementing, that of updating a value in my database.
Since there is a value to enter in a textbox, I cannot load everything (well I think) on another page and refresh every second ...
Here is my complete code and I can't refresh Enchere_Max

Sans-titre.png
index.php
<?php try{$Stat = $pdo->query("SELECT * FROM tb_shop_enchere"); while($data = $Stat->fetch(PDO::FETCH_ASSOC)) { $MyId = $data["NumId"]; ?>

<div id="Enchere_<?php echo $MyId; ?>"></div>

<script>
$(document).ready(function() {
	setInterval(function() {
		$('#Enchere_<?php echo $MyId; ?>').load('refresh.php');
	}, 1000);
});
</script>

<?php }}catch(PDOException $e){echo "<div class='alert alert-danger'>".$e->getMessage()."</div>";} ?>

Open in new window


refresh.php
<?php try{$Stat = $pdo->query("SELECT * FROM tb_shop_enchere WHERE NumId = '".$MyId."'"); while($data = $Stat->fetch(PDO::FETCH_ASSOC)) { ?>

<?php echo $data["Enchere_Max"];?>

<?php }}catch(PDOException $e){echo "<div class='alert alert-danger'>".$e->getMessage()."</div>";} ?>

Open in new window

Maybe my method is not the right one, so if you can help me it would be nice.
0
Hi

In Phaser, what is the expected way to start off a solid phaser game?..

What I mean is if Phaser games study the dimensions of the device or the input capabilities? ( as they vary amongst devices.. and might even alter the game, - desktop/tablet/phone)
When do games deduce if they are desktop/mobile? Some, like Slither probably don't care.
I'd like to put up a script that prepares my game which involves pics and nearby text selection.
How do I put up such a script that loads images onto the screen, draws text, lines. - and includes mouse selection and touch? The image object!
0
I am doing some test provisioning into a Dev LDAP server. When I send the password, it goes in as plain text.... but the PROD version is SSHA hashed... Is that just a configuration that's not right on the dev server or is there something I need to do to that password before I push it in so it shows up as SSHA hashed? I can't find a topic called LDAP, btw
0
I'm working on a ticket whose title is, "Redirect from form is not validated."

Not sure what that means.

Here's what I know:
The app is using "express-session"
I'm storing the session data in "user-sessions"

try {
  let sessionObj = session({
    secret: process.env.SESSION_SECRET,
    store: new MongoStore({
      mongooseConnection: global.db,
      collection: 'user_sessions'
    }),
    cookie: {
      maxAge: (60 * 60) * 1000, // 1 hour - milliseconds
    },
    rolling: true, // resets the cookie max age on each request
    resave: false,
    saveUninitialized: true
  });

  app.use(sessionObj);
} catch (err) {
  console.log('Error: ', err);
  return false;
}

Open in new window

After successfully logging in, I can do a "console.log(req.session);" and see all of my session data.

Here's the file coming out of my "services..."

  async auth(email, password) {
    const isDev = (process.env.ENV == 'local' || process.env.ENV == 'dev');
    let match = {
      email: email,
      active: true
    };

    try {
        let user = await this.loadUser(match);        
      // validate the password hash
      if (!isDev) {
        await this.checkPasswordHash(password, user.password);
      }

      return this.success(user);
    } catch (err) {
      console.log('Error: ', err);
      return this.error(err);
    }
  }

Open in new window


And here's the login route:

router.post('/login/auth', async (req, res) => {
  if (typeof req.body.email == 'undefined' || typeof req.body.password == 'undefined') {
    flash.add(req, 'Please enter a valid email address and password before trying again.', 'danger');
    return res.redirect('/login');
  }

  let resp = await user.auth(req.body.email, req.body.password);

  if (resp.error) {
    flash.add(req, 'The provided email address and password combination is invalid. Please try again. If you need further assistance, please call 855.581.9910.', 'danger');
    return res.redirect('/login');
  }

  req.session.user = resp.data;
    await user.lastLogin();//Update lastLogin date
  let redirect = (req.body.redirect != '') ? req.body.redirect : '/';

  res.redirect(redirect);
});

Open in new window


This may all be golden and I just don't know it. But before I go asking around, I wanted to do my due diligence and make sure that I wasn't missing something.

Does this look OK? If something is jacked up, what's lacking and how can I fix it?
0
I'm having trouble with finding the correct syntax to catcha 404 error from my api call. Currently if there is a 404 it never appears to make it to the:

.catch(() => this.setState({ hasErrors: true }))

Open in new window


part of the call. I'm currently searching for an example but can't seem to find a simplified one.

fetch snippet

        fetch('http://localhost/MICROSERVICES/TestAPI1/api/Users/test/' + mid)
            .then(res => res.json())
            .then((res) => {
                setUserInfo({userInfo: res});
            })
            .catch(() => this.setState({ hasErrors: true }))

Open in new window

0
Hi,

I need your help please.

I'm trying to validate an email address

function ValidateData() {
        //debugger;
        var StartCreateDate = $('#FromCreatedDate').val();
        var EndCreateDate = $('#ToCreatedDate').val();
        var StartMigrationDate = $('#FromMigrationDate').val();
        var EndMigrationDate = $('#ToMigrationDate').val();
        var SendToEmail = $('#SendEmailTo').val();
       
        if ((StartCreateDate != null && EndCreateDate != null) && (StartCreateDate > EndCreateDate)) {
            alert("From create date must be greater than to create date")
            return false;
        }
        if ((StartMigrationDate != null && EndMigrationDate != null) && (StartMigrationDate > EndMigrationDate)) {
            alert("From migration date must be greater than to migration date")
            return false;
        }
        if (SendToEmail "doesn't have the correct format")  //Here I want to validate my email address $('#SendEmailTo').val();
        {
            alert("Email format is incorrect")
            return false;
        }

        return true;
    }

Open in new window



Thank you,
0
I'm trying to figure out why my code is not working properly?  I never get to the function _dtmSetProdType (#2 console.log) from my attempt to add the listener? You can test by going to https://apply.essexcredit.com/#blockdtm (***ensure you use the #blockdtm in the URL) and on the first page, run the code in dev. console and select the  product selectHere is my test code:
function _dtmSetProdType() {
    console.log("2 #### ====> IN  _dtmSetProdType");
    var selProdOption = event.target.value;
    console.log("3 #### ======> selProdOption : " + selProdOption);
};

function _dtmCheckProductSelect() {
    var prodSel = document.evaluate("//form/div/div/div/div/div/div/div/div/div/div/div/div/div/div/div[@class='option-selected']", document, null, XPathResult.ANY_TYPE, null).iterateNext();
    if (prodSel) {
        console.log("1 #### ====> calling  _dtmSetProdType");
        prodSel.addEventListener('change', _dtmSetProdType);
    } else {
        setTimeout(_dtmCheckProductSelect, 1000);
    }
};

_dtmCheckProductSelect();

Open in new window

What I want is each time a selection is made, to grab that value of the select. Thanks!
0
I need to build an html form that collects data entered from the user and then creates json to be used for an API call.  The format that the JSON needs to placed in is hierarchical and I'm not sure how to do that.

This is what the JSON should look like and each value should be coming in from the html form.  

{
"request": {
        "subject": "Unable to fetch mails",
        "description": "I am unable to fetch mails from the mail server",
        "requester": {
            "id": "4",
            "name": "administrator"
        },
        "impact_details": "Routine tasks are pending due to mail server problem",
        "resolution": {
            "content": "Mail Fetching Server problem has been fixed"
        },
        "status": {
            "name": "Open"
        }
    }
}'

Open in new window

0
I would like to get an ajax call working for an autocomplete text field, it fetches players' names.  In the same query that gets the names I can retrieve the phone number of each player.  

What I want to do, is that when the user picks the player from the list, I want to flag up if the chosen player has no number stored. I don't want to show the number on the screen at all.

What I have done so far can be tested at http://www.col-b.uk/fines_text.php

I have little knowledge of javascript, so I have included first_name, surname and tel_mobile fields as one string of data to be returned from the selection.  

1. I need to show/hide the 'No number stored' message at the right times.
2. I never want to show the number on the screen.
3. In this test data, the only person with no number is Steve Johnson.

Data
DROP TABLE IF EXISTS players;

CREATE TABLE players (
  id                int AUTO_INCREMENT NOT NULL,
  first_name        varchar(25) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  surname           varchar(25) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  tel_mobile        varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci,
  /* Keys */
  PRIMARY KEY (id)
) ENGINE = MyISAM;

INSERT INTO players (first_name, surname, tel_mobile) VALUES ('Alan','Johnson','00123 121212');
INSERT INTO players (first_name, surname, tel_mobile) VALUES ('Albert','Johnson','00123 121212');
INSERT INTO players (first_name, surname, tel_mobile) VALUES 

Open in new window

0
I am using jQuery to add a Class to the first <p> selector within a div wrapper with a class .addline using this:
jQuery( ".addline p" ).first().addClass( "leftline" );

This works great and adds that class to only the first <p class="leftline"> within <div class="addline">

but sometimes <p> is not the first selector I want to add that class to. So I need jQuery to only look for the first of one of these: var ary = ['p', 'h2', '', 'h3', 'li', 'ol'];

I thought maybe I could do something like this:

var ary = [$p_selector, $h2_selector, $h3_selector, $li_selector, $ol_selector];

var $p_selector =  jQuery( ".addline p" ).first();
var $h2_selector =  jQuery( ".addline h2" ).first();
var $h3_selector =  jQuery( ".addline h3" ).first();
var $li_selector =  jQuery( ".addline li" ).first();
var $ol_selector =  jQuery( ".addline ol" ).first();

Then use an IF statement or something.?

Here is a video to help explain.
https://www.loom.com/share/27fd9940e39c4bcc8c30a65965dc3c2c

Sample Page: https://allgood.flywheelsites.com/all-goods-comprehensive-guide-to-non-toxic-natural-remedies-for-eczema/
0
I copied the following codes from mvc/razor angular c# web app. I would like to learn that usually how the {User.FirstName} got the data source from.  

Just hope to get someone who know about mvc/angular.

Thanks



<ul class="nav navbar-nav" id="centeredInNav"><li><a href="tel+:112222">for questions Call 
                {{User.FirstName}} {{User.LastName}} at {{User.Phone | tel}}
            </a></li></ul>

Open in new window

0
If you go to https://apply.essexcredit.com/ on the first page, you'll see a select "What type of loan are you interested in? ". I need to set an event listener on this element and grab the value being selected.(RV or Boat).  Javascript only. Please see image

Screenshot of select
*** I can't touch/change the code on the page. I have to use a TMS to inject my code. ***

Thanks!
0
How would I detect if this element is on the current page and visible? Using JavaScript and NOT jQuery.

<p><strong>Before you Start</strong></p>

Open in new window


I'm fairly sure this function will suffice with detecting if visible.

    function _dtmIsVis(elem) {
        if (elem === null) {
            return false;
        }
        return !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length);
    };

Open in new window


Thanks!
0
I am using Elementor plugin with WooCommerce in WordPress and since updating the plugin to latest version 2.9.2, The plugin stopped working. When I click on edit with Elementor it forces me to enable safemode and this is the error it logs in the debug logs

 [error X 2][/wp-content/uploads/elementor/editor.min.js:7:49075] this.config.initial_document.urls is undefined 

Open in new window


I have tried to reach out the plugin developer but no response from them at all as this a free plugin so comes with no or limited support.

I am hoping if someone from the Experts Exchange community can advise in how to fix this error.

Thanks and appreciate it
0
I'm getting this error and I don't know how to fix it.

I'm using GraphQL with a React front end. Everything is looking good, but on the back end I'm getting this:

C:\wamp64\www\adm\node\api\node_modules\graphql\validation\validate.js:108
    throw new Error(errors.map(function (error) {
    ^

Error: There can be only one type named "RootQuery".
    at assertValidSDL (C:\wamp64\www\adm\node\api\node_modules\graphql\validation\validate.js:108:11)
    at buildASTSchema (C:\wamp64\www\adm\node\api\node_modules\graphql\utilities\buildASTSchema.js:71:34)
    at buildSchema (C:\wamp64\www\adm\node\api\node_modules\graphql\utilities\buildASTSchema.js:462:10)
    at Object.<anonymous> (C:\wamp64\www\adm\node\api\graphql\schema.js:3:18)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Module.require (internal/modules/cjs/loader.js:852:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (C:\wamp64\www\adm\node\api\app.js:9:23)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at 

Open in new window

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.