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.

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
I am not very comfortable with javascript, but I am working with a web site where I would like to make a small change, if I can figure out how to do it.

There is a page where users can view some codes associated with clients. On this page, users can - among other things - add new codes. There is an "Add/Edit" button that, when pressed,  allows the user to add new codes. When the "Add/Edit" button is pressed, a dialog box pops up containing various controls that allow the user to configure and add a code. The issue I am trying to change is that, when this dialog box has been displayed, if the user for some reason clicks outside the dialog box, it immediately closes losing any configuration information the user may have entered. If they still want to add a code, they click the "Add/Edit" button again and start over. I want to change it so that the dialog box does NOT close if the user clicks outside the dialog box, but only closes when the user presses either the "Cancel" or the "Save" button. Also, the dialog box should retain any information the user has already entered.


I have attached screenshots of the main form (screen1) and the dialog box (screen2).

I don't need exact code for this particular application, I just need some representative code to see how this could be done in javascript. I know in Windows, there are various modes that can be specified when displaying a window, so maybe it is as simple as that. But maybe not.
Screen1.JPG
Screen2.JPG
0
I'm working on my understanding of how to make an API call in my react application in a functional/stateless component. I've made successful API calls in my class component but for some reason in my functional component, the fetch call is pre-pending (attaching to the front) something extra to my API call and I don't understand why. The call is pre-pending "local:3000" to the front of my API call which is making the call look like:

"localhost:3000/localhost/MyAPICall/path"

and breaking the API call I'm sure.  Why is this happening and how do I fix it?

 my functional component
const Login = () => {

    const [hasError, setErrors] = useState(false);
    const [planets, setPlanets] = useState(null);
  
    useEffect(() => {
      async function fetchData() {
        const res = await fetch("localhost/MICROSERVICES/TestAPI/api/Users/test/1");
        res
          .json()
          .then(res => setPlanets(res))
          .catch(err => setErrors(err));
      }
  
      fetchData();
    }, []);
  
    return (
      <div>
        <span>{JSON.stringify(planets)}</span>
        <hr />
        <span>Has error: {JSON.stringify(hasError)}</span>
      </div>
    );

};

Open in new window

0
After upgrading a very small server from Apache 2.2 to Apache 2.4, some images called from an included file no longer appear on the page.

The host uses scripted HTML.  The SHTML files include an HTML header template.  I have confirmed that the HTML header is being included properly in the outgoing and received SHTML file.

As a source file on the server (trimmed for brevity):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>
<HEAD>
<TITLE>domainname.com</title>
<META NAME="description" CONTENT="bla bla bla.">
</HEAD>

<BODY BGCOLOR="#FFD700">

<!--#include virtual="/includes/StandardHeader.html" -->

<!-- Content section begins here, below the header -->
(file continues) ...

Open in new window


As received by Firefox:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>
<HEAD>
<TITLE>domainname.com</title>
<META NAME="description" CONTENT="bla bla bla.">
</HEAD>

<BODY BGCOLOR="#FFD700">

<!-- Included header file to be inserted below BODY -->

<DIV ID="header">

<TABLE BORDER="0" WIDTH="100%" CELLSPACING="0" CELLPADDING="0" BGCOLOR="#6699FF"><TR>
<TD>
<script type="text/javascript">
<!--
 var image_number = 0;
 var image_count = 12;
  function randomimage() {
        image_number = 1 + Math.floor(Math.random() * image_count);
        return image_number;
    }
  document.write("<img src='http://www.mydomainname.com/headerimages/header" + randomimage() + ".png'>");
//-->
</script></TD>
<TD><IMG 

Open in new window

0
I am relatively new to Wordpress and am trying to add code to a page.
Here is the code:

<div id="libchat_97a02353a0afcdc8a5eab67b19250e53"></div><script type="text/javascript" src="https://v2.libanswers.com/load_chat.php?hash=97a02353a0afcdc8a5eab67b19250e53"></script>


Although I have worked with PHP, javascript, and html extensively, I am at a loss on how to get Wordpress to recognize this code. I use the html editor on the page and the result is it simply displays the code, it should display a widget.

Any tips would be greatly appreciated.
0
I open a modal by clicking on a button that's in a table. There's one of these buttons in each row. The modal is intended to provide a way of editing the data for the user in the row containing the button that was clicked. The modal opens, but how do I:

1. initiate the JS for the modal's edit process
2. pass the id from the row to JS
3. set the focus on the first input text box
4. I plan to use JS to confirm the delete request as well

I'm fine to use AJAX for updating tables. I've nearly got all the mechanics of the application working without using JQuery, Bootstrap or any other libraries and would like to keep it that way. This is likely the only Web app that I'll ever write and requiring more work is acceptable. I read that the <dialog> element isn't supported by Edge or IE, so that's not an option. Thank you for any assistance that you can provide.
sampleModal.php
0
I've gotten spoiled using Nodemon and while I've got that installed on the app that I'm working on (I didn't build it, I'm just working on it), it doesn't restart the server in the way I'm accustomed to and I don't know why.

Here's the way things look on my Command Line:

b.gust@AHA-DT-BGUST2 MINGW64 /c/wamp64/www/bsmart (BRUCE-code-cleanup)
$ npm start

> cams@1.0.0 start C:\wamp64\www\bsmart
> nodemon index.js

[nodemon] 2.0.2
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
Listening on PORT: 3000

Open in new window


...and here are my scripts:

{
  "name": "cams",
  "version": "1.0.0",
  "description": "Client Acquisition Management System",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
	"start": "nodemon index.js"
  },
  "author": "Mitch Cannon",
  "dependencies": {
    "aws-sdk": "^2.382.0",
    "bcrypt": "^3.0.2",
    "body-parser": "^1.18.3",
    "connect-mongo": "^2.0.3",
    "csv-stream": "^0.2.0",
    "dotenv": "^6.2.0",
    "express": "^4.16.4",
    "express-fileupload": "^1.0.0",
    "express-session": "^1.15.6",
    "express-sessions": "^1.0.6",
    "js-md5": "^0.7.3",
    "jsonwebtoken": "^8.4.0",
    "lodash": "^4.17.10",
    "moment": "^2.23.0",
    "moment-timezone": "^0.5.23",
    "mongodb": "^3.1.10",
    "mongoose": "^5.4.0",
    "multer-s3": "^2.9.0",
    "node-utils": "",
    "nodemailer": "^6.2.1",
    "nodemon": "^2.0.2",
    "papaparse": "^4.6.2",
    "request": "^2.88.0",
    "socket.io": "^2.2.0",
    "twig": "^1.12.0",
    "unzipper": "^0.9.11",
    "uuid": "^3.3.2",
    "validator": "^10.10.0"
  }
}

Open in new window


What am I missing that would allow for Nodemon to operate in the way I'm accustomed, as far as me making a change in the code and the server automatically restarting?
0
I have been working on this problem for several hours and given it my best shot. I am tying to detect a change in an INPUT box that is changed dynamically by Javascript.

I have distilled my problem down to this simple code.

<html>
<head>

</head>
<body>
  <form class="" action="index.html" method="post">
      <input id="myInput" type="text" name="myCountry" placeholder="City/Town/Village name" value="">
  </form>
  
  <div id="myText">-----</div>
</body>
</html>

<script>
document.getElementById("myInput").addEventListener("change", myChangeFunction);

document.getElementById("myInput").value = "James";

function myChangeFunction (){
  document.getElementById("myText").innerHTML = document.getElementById("myInput").value;
}
</script>

Open in new window


My javascript puts an eventlisterner "change" on the input box.

It then changes the value in the input box to "James".

My question is this, I need an eventlistener that will 'hear' this change and so change the text in the div element with an id of myText to the value, in this case James.

How can we use eventlisteners to detect the dynamic change in the input box please?

Thank you
James
0
I researched Csrf and CORS. what I understood was

say User A is authorized to access a site, but it is possible to exploit and execute say javascript from user A's browser to perform unintended actions from his/her browser.

To avoid this, browsers has same origin policy , where If I have a website say in one domain,

www.mywebsite.com and I have some javascript in my web page that makes an AJAX calls to say a api in a different domain, say www.yourdomain.com/api/users or something like this.

browser will see my domain is mywebsite and the call is being made to yourdomain.com and it will block it.

to be able to make a successful call from mywebsite to the api hosted at www.yourdomain.com. the yourdomain server   has to send Access-Control-Allow-Origin in response .

I am not clear on one thing,

so say,

1. if i make an ajax call to the api ( a get call)
2. does the api send the Access-Control-Allow-Origin header in the response header, along with the data for the get call?

Question:


1. is this done in 1 call or is it done in two steps, first browser calls to see if the server sends back
Access-Control-Allow-Origin in the header and then it issues a Get call?

2. if the call is not from the browser , and my backend code calls this api, does the CORS policy apply then?

I apologize for the long questions, I wanted to see if i can explain what i understood before I asked the question.
0
I'm working on a Nodejs application and I want to give the user the opportunity to view the password they're attempting to set.

I've seen this option before where you can click on an "eye" icon and you can see the characters that would otherwise be represented by asterisks.

How do you pull that off?
0
I have a functional control that contains a form that has a couple of inputs on the form. I was attempting to use a single handleChange function to process the data input into the input fields but, I ran across a problem that I did solve, by separating the handleChange function into 2 functions: 1 for each input control, but I don't understand why I had to do it this way. I'm including my code and want to know why I had to do it this way, or was I missing something when I attempted to handle it in 1 handleChange function.

The problem (what wasn't working): When I would type into the password field, it would post the input in the username input field. When I stepped through the handleChange code, the control that always showed up was the username control, EXCEPT for when the page first loads. When the page would first load, if I typed into the password control, when I stepped through the handleChange function, the password control would be correctly passed to the function. After that, no matter which field I typed into, the control passed to the handleChange function was ALWAYS the username control.

WHAT DIDN'T WORK
    const [username, setUserName] = useState('');
    const [password, setUserPassword] = useState('');

    const handleChange = (e) => {
        const { name, value } = e.target;

        if (e.target.name = "username")
            setUserName( () => value );
        else
            setUserPassword( () => value );
    }

    return (
        <div 

Open in new window

0
Hi Team,

my requirement is like select 1 from drop down it means January so only January should be enable on date picker , other months should be disable . if need more clarification please let me know .
below is my code please help me out where i m doing wrong.



var monthYear=0;
monthYear = $('#mYear').val();; 
		alert(mYear);
		$("#pdate").datepicker
			({
	   			minDate:"dateToday",
	   			dateFormat: 'dd/mm/yy',
	   			changeMonth: true,
	   			numberOfMonths: 1,
	   			onClose: function (selectedDate) {
	 						$("#pdate").datepicker("option", "minDate", selectedDate);
	   								},
	   							//Code to disable dates according to selection
	   							beforeShowDay: filterDate
			});
 var filterDate = function(date) {
     if(monthYear=='0'){
       return [true];
     }else{          
       return [(1+date.getMonth()) == monthYear];
     }
 }
  $(document).ready(function() {  
	 $("#sdata").click(function(evt) {
		evt.preventDefault();
		 if(save()){
			$.ajax({
				url: "Test.jsp",
				type: "post",
				data: {
				pS:$('#pS').val(),
				pType:$('#pT').val(),
				pCode:$('#pC').val(),
				mYear:$('#mYear').val(),
				pDate:$('#pdate').val(),
				ppDate:$('#ppdate').val(),
				bDate:$('#bdate').val()},
				success: function(responseFromServer) {
	            	$.each(responseFromServer, function(resultMessageKey,resultMessageValue) {	
	                    $('#content').html(resultMessageKey);
	                });
	            	getClearDateValues();
	    

Open in new window

0
Hi All

I'm trying to get the below code to work using html and javascript where it looks at a network drive called z: and shows the last photo taken (the file name varies, images created begin with "capt and end in a number, i.e. capt5578.jpg - wildcard needs to be used) based on timestamp, see below

<html>
<head>
</head>
<body>
<script type="text/javascript">
    function handleResponse(req) {
        if( req.readyState == 4 ) {
         document.getElementById('show').innerHTML = req.getResponseHeader("Last-Modified")
        }
    }
    function createRequestObject() {
        if(window.XMLHttpRequest) {
            req = new XMLHttpRequest();
        } else if(window.ActiveXObject) {
            req = new ActiveXObject("Microsoft.XMLHTTP");
        }
        return req;
    }
    function makeRequest()
    {
      var req = createRequestObject();
    	if (req) {
		req.onreadystatechange = function() { handleResponse( req ); };
		req.open("HEAD", "z:/capt*.jpg",true);
		req.send(null)
	}
    }
    function reloadImage() {
        var now = new Date();
        if (document.images) {
            document.images.myobject.src = 'z:/capt*.jpg?' + now.getTime();
            makeRequest()
        }
        setTimeout('reloadImage()', 15000);
    }
    setTimeout('reloadImage()', 0);
</script>
</body>
</html>

Open in new window


The issue here is I cannot get this to work. I'm not sure if I'm doing anything wrong here. Any help is greatly appreciated.
0
I have a PDF with two text fields on it "Today" and "Tomorrow".  I am trying to have the form read the "Today" field and then display "Today" + 1 day in the "Tomorrow" field.  So, if the "Today" text field is 2/18/2020 then the "Tomorrow" text field will read 2/20/2020.  Here is the code I have so far:
this.addScript("init", "var d = new Date(); var f = this.getField(\"Today\"); if (f.value==\"\") f.value = d; var t = this.getField(\"Tomorrow\"); t.value = t.setDate(d+1);")
0
React newbie question: What are the advantages/disadvantages of using a form to submit a click action vs. using a button to handle a click event? Are there links or articles that compare the two?
0
I am familiar with Coldfusion and a little javascript. I am not familiar with calling APIs. I am trying to understand how I can use the OpenSRS API. Unfortunately none of their examples use Coldfusion. Can someone help me understand how I would use their API using Coldfusion

See https://domains.opensrs.guide/docs
0
I have a site I am working on that when you do a search for a post_type, it won't change the title.  I have the following hack but it does not work because it runs before the jQuery library is included.

function searchfilter($query) {
    if ($query->is_search && !is_admin() ) {
        if(isset($_GET['post_type'])) {
            $type = $_GET['post_type'];
                if($type == 'product') {
                    ?>
    <script>
    (function($){
        var term = '<?php the_search_query(); ?>';

        $('.archive-title').text("Your Search for: " + term + "");
        })(jQuery);
    </script> 
    <?php
                }
        }       
    }
return $query;
}
add_filter('pre_get_posts','searchfilter');

Open in new window


You can see what I mean here: https://gardenersstage.wpengine.com/?s=seeds&post_type=product
"Shop Our Store"  Should say "Your Search for: " + term + "" Or do you know how to change the title of the page if the post type is set?
0
Here's the code that's getting triggered by the "user-form-show" method:

$(window).on('user-form-show', function(e, userId, opts){
    // prep the modal
    $uModal.find('.loading').show();
    $uModal.find('.main').hide();

    // show the modal loading screen
    $.magnificPopup.open({
      alignTop: true,
      items: {
        src: $uModal, // can be a HTML string, jQuery object, or CSS selector
        type: 'inline'
      }
    });

    // clear the cached data
    data = {};

    // clear the form from any previous data
    clearForm();
           

    // load the data if a valid id is provided
    if (typeof userId != 'undefined' && userId != 'new') {
      loadFormData(userId);
    } else {
      // set the id for a new user
        loadedUserId = 'new';
        // load drag & drop members 
        teamDragula(userId);

        $form.find('#user-role').attr('data-user-id', loadedUserId);
      // force the password fields
      $form.find('.btn-change-password').replaceWith( $passwordForm.clone() );
      $form.find('.btn-cancel-password').closest('.col').remove();

      // show the form
      $uModal.find('.loading').hide();
      $uModal.find('.main').show();
    }
  });

Open in new window


The line that I'm wanting to understand is this:

$form.find('#user-role').attr('data-user-id', loadedUserId);

Earlier in the file, $uModal was defined like this:

var $uModal = $('#modal-user-form'),
      $form = $('#user-form'),
      $passwordButton = $form.find('.btn-change-password').clone(),
      $passwordForm = $form.find('.password-template').clone().removeClass('d-none'),
      data = [],
      loadedUserId = '',
      passwordRegex = {
        upper: /[A-Z]{1,}/,
        lower: /[a-z]{1,}/,
        number: /[0-9]{1,}/,
        special: /[\!\@\#\$\%\^\&\*]{1,}/,
        total: /.{8,}/
      };

Open in new window


When you follow the trail as far as the "user-form.html.twig," you find that the portion of code that I've got in bold is referring to this:

<select id="user-role" name="user[role]" class="form-control mdb-select md-form" required>
               {% if roles is not empty %}
                {% for role in roles %}                
                    <option value="{{role}}" {{role=='Sales Representative'?'selected="selected"':''}} >{{role}}</option>
                {% endfor %}
                {% endif %}
            </select>


My question is: Where is "data-user-id?"

I'm thinking that the referenced SELECT would have a "user-id" value attached to is and the ".attr('data-user-id', loadedUserId" code is populating that value with the "loadedUserId" value, yes?

What is "att('data-user-id', loaded.UserId)" doing?
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.