JavaScript

120K

Solutions

41K

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 wanted to change the background color of a DIV (id=appdtic) on every click on all links; the bg-color should stay yellow for 3 seconds, and then the browser should load the link provided. Here's the code that does NOT work:

<div id="appdtic">appdtic</div>
<div><a href="tst1.html">first link</a></div>
<div><a href="tst2.html">second link</a></div>
<div><a href="tst3.html">third link</a></div>
<div><a href="tst4.html">fourth link</a></div>
<script>
   function dofunc() {
      alert('func alert!');
   }
   var elements = document.getElementsByTagName('a');
   for(var i = 0, len = elements.length; i < len; i++) {
      elements[i].onclick = function () {
         document.getElementById('appdtic').style.backgroundColor='yellow';
         alert('some alert!');
         setTimeout(dofunc, 3000);
      }
   }
</script>

Open in new window


The alerts inside the functions are for testing purposes. But, this doesn't work as expected. For me, it seems that setTimeout is ignored. What is wrong in the code?

For comparison, here is another code that works, although id does something else (it waits 3 seconds before actually submitting the form):

Yes, the button is not of a submit type, and is outside the form, so to circumvent the default event of the form.

<form name="formular" id="formular" method="post" action="test2.php">
</form>
<input type="button" value="send" id="submit">
<script>
    function submitForm() {
        document.getElementById("formular").submit()
    }

    document.getElementById('submit').onclick = function() {
        setTimeout(submitForm, 3000); 
    }
</script>

Open in new window


Thank you for your time.
0
Optimize your web performance
LVL 1
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

I am using Javascript, HTML, Json and PHP.  The emails were sending but now they are not.  Any help is appreciated.  Thank you.

www.mediascrubber.com/videos.html


<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script>
$(function() {
  $("#myform").on('submit', function(e) {
    e.preventDefault();
    $.ajax({
      url: '//jsbin.com/vufeyag.json',
      dataType: 'json',
      data: $("#myform").serialize()
    }).done(function(d) {
      if (d.success==true) {
        $("#myform").hide();
        $("#results").text("Thanks!").show();
      }
    });
  });
});
</script>>

Open in new window


<?php

$webmaster_email = "ds@mediascrubber.com";
$email_address = $_REQUEST['email_address'] ;

function isInjected($str) {
	$injections = array('(\n+)',
	'(\r+)',
	'(\t+)',
	'(%0A+)',
	'(%0D+)',
	'(%08+)',
	'(%09+)'
	);
	$inject = join('|', $injections);
	$inject = "/$inject/i";
	if(preg_match($inject,$str)) {
		return true;
	}
	else {
		return false;
	}
}


if (!isset($_REQUEST['email_address'])) {
header( "Location: $feedback_page" );
}
elseif ( isInjected($email_address) ) {
header( "Location: $error_page" );
}
else {
mail( "$webmaster_email", "Subscruber",
 
   "From: $email_address" );
   

}
$jsonurl = "http://api.wipmania.com/json";
$json = file_get_contents($jsonurl);
var_dump(json_decode($json));
?>

Open in new window


<form id="myform" class="form-horizontal" action="send_mail.php" method="post">
				<div class="input-group">
                <input type="text" name="email_address" class="def-input" placeholder="Your Email Here">
                <span class="input-group-btn">
                <button class="btn-form btn" input type="submit">Subscribe</button>
                </span>
                
				</div>
                </form>
                <div id="results" style="display: none;"></div>

Open in new window

0
I want to produce the following output:
[
    [
        "a", "d", "e", "f"
    ],
    [
        "b", "d", "e", "f"
    ],
    [
        "c", "d", "e", "f"
    ]
]  

Open in new window


The javascript code that I create is the following:
var result = [];
var data1 = ['a', 'b', 'c'];
var data2 = ['d', 'e', 'f'];
for (var i = 0; i < data1.length; i++) {  
  if(i===0){    
        data2.splice(0,0,data1[i]);
        console.log(data2);
        result.push(data2);
        }else{
         data2.splice(0,1,data1[i]);
         console.log(data2);
         result.push(data2);
        }  
}
console.log(result);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Open in new window

If you see in the image below the data2 array elements (specially data2[0] & data2[1]) appears wrong in the console and finally at the result array...
console imageWhat is wrong?!!!
0
I have a countdown clock on my homepage.  I don't know where I can set the parameters....any help appreciated.

www.mediascrubber.com

<section class="event-countdown" style="background: url(assets/images/bg-event2.png);  background-size:cover; background-attachment: fixed;">
      <div class="overlay"></div>
      <div class="container sec-hq-pad text-center">
        <div class="title-underlined ">
          <h1>Pre-Order</h1>
        </div>
        <h2 class="fest-name">"August 4, 2017"</h2>
        <!--p>London, UK</p-->
        <ul class="countdown sec-h-pad no-h-padding">
          <li>
            <span class="days">00</span>
            <p class="days_ref">Days</p>
          </li>
          <li>
            <span class="hours">00</span>
            <p class="hours_ref">Hours</p>
          </li>
          <li>
            <span class="minutes">00</span>
            <p class="minutes_ref">Minutes</p>
          </li>
          <li>
            <span class="seconds">00</span>
            <p class="seconds_ref">Seconds</p>
          </li>
        </ul><!--/.countdown -->
        <a href="" class="def-btn btn-bg-light mar-t-20" data-text="See More"><span>See More</span></a>
      </div>
    </section>
    <!-- Event Countdown End -->

Open in new window


I found this but it doesn't seem to change anything.
 // -------------- Countdown -------------- 

  $('.countdown').downCount({
    date: '08/04/2017 12:00:00',
    offset: +10
  }, function () {
    alert('WOOT WOOT, done!');
  });

Open in new window

0
0
I have the cloning, piece working fine, but just realized when I click "Add Flight" to clone and try to select the Departure Time only my original picker is working.  How can I fix this?

http://groupplanner.gallitin.com/flight/create?tripID=21&tripName=Iowa&depart=07%2F20%2F2017&return=07%2F27%2F2017
0
I have this html:

<div class="col-sm-3 col-xs-3" style="padding-top:14px;"><input type="checkbox" name="ihzt" <? if ($_SESSION['ihzt'] == "on") { ?>checked <? } ?>>&nbsp;Irrigation<br>
	<span style="padding-left:20px;"><input type="radio" value="cf" name="feed" <? if($_SESSION['feed'] == "cf") {?>checked<? } ?>>&nbsp;Chemical Feed</span><br>
	<span style="padding-left:20px;"><input type="radio" value="ncf" name="feed" <? if($_SESSION['feed'] == "ncf") {?>checked<? } ?>>&nbsp;Non-Chemical Feed</span></div>

Open in new window


if the checkbox ihzt is checked, I want to FORCE one of the two radio buttons named "feed" to be selected.

I have this Javascript:

if (document.st.ihzt.checked) {
					cfok = false;
					if (document.st.feed.value == "ncf" || document.st.feed.value == "cf") {
						cfok = true;
					}
					if (! cfok) {
						alert("Please check either Chemical or Non-Chemical feed.");
						return false;
					}	
				}

Open in new window


Doesn't work.

The form name is st.

What's the trick?
0
I have recently started learning about the FuelPHP framework and I have a question that I thought I would post here first, instead of the FuelPHP Forum.

I have been working on understanding how to use the framework as intended by the creators, and I think I'm doing a fair job of that, except possibly with regards to using external jQuery libraries.

I have a simple CRUD application that I built  as a proof of concept for using a third party jQuery DateTimePicker library.

This is the jQuery DateTimePicker library that I found and used.



FuelPHP DateTimePicker Sample - dtpsample
This is not including the public asset folder that contains the actual Javascript and CSS.

Model

fuel/app/classes/model/dtpsample.php

This includes data validation.  Each field is important.  It is important to not rely only on the Javascript front end.  I could improve the validation, but this is a start.

<?php
class Model_Dtpsample extends Model_Crud
{
	protected static $_table_name = 'dtpsample';
	
	public static function validate($factory)
	{
		$val = Validation::forge($factory);
		$val->add_field('name', 'Name', 'required|max_length[255]');
		$val->add_field('event_date', 'Event Date', 'required');
		

		return $val;
	}

}

Open in new window


View Template

fuel/app/views/template_dtpsample.php

I want to specifically point out this piece of code regarding my question. The main question I have is have it properly separated concerns?  I want to have the application display the Date and Time selected in the input box directly above the calendar/time select control as indicated by this screenshot.

dtpsample create new entry
Notice that I have used  Asset::css and Asset::js to load the require asset files.


Open in new window

0
I have a situation where when the user clicks on a link, it takes a while for that URL to load. If you look closely at the tab, you can see that it's churning, but there's nothing on the page to indicate that you've clicked the button and the page that you're expecting to see is loading.

I want to create an alert box that assures the user that they've clicked on the button and the next page is loading.

Here's what's on the initial form (AJAX):

$.post('api_nex.php?p=verify&displayLinks=portal', out, function(data)
                        {
                              if(data.indexOf("We were unable to match the information you provided")!==-1)
                              {
                                    $('.step_1').show();
                                    $('#window').html(data);
                              }
                              else
                              {
                                    $('.step_1').hide();
                                    $('#window').html(data);
                              }
                        });

Here's the code that's being returned in the event of a successful post:

      <script>
                                                      
                              $('#header_text').html('Click on the "Yes" button if the name listed below is you.<br>Otherwise, click "No."');            
                              
                              $('#verifyUseryes').click(function(){
                                    window.location='$portalLink';
                              });
                              $('#verifyUserno').click(function(){
                                    $('#header_text').html('Please enter your personal information and click on "submit!"');            
                                    $('.step_1').show();
                                    $('#window').html('');
                              });
                              </script>

The "$portalLink" is the URL. That drags a little bit, as far as loading. Is there a way to set up an alert that lets the user know that the page is loading that…
0
I'm trying to apply a minor customization to a WordPress admin screen, and would like to figure out how to populate the closest text input field with radio button value on click using Javascript / jQuery.  

The HTML that I currently have in place is as follows:

 <div class="rwmb-input">

  <input size="30" type="text" class="rwmb-text" id="fave_plan_title" name="floor_plans[0][fave_plan_title]">

  <div class="floor-plan-titles">

      <input class="plan-title" type="radio" name="plan-title" id="plan-title1" value="First Floor">First Floor 
      <input class="plan-title" type="radio" name="plan-title" id="plan-title2" value="Second Floor">Second Floor
      <input class="plan-title" type="radio" name="plan-title" id="plan-title3" value="">Custom

  </div>

</div>

Open in new window


To clarify .. I'd like to have it so that when you click on one of the 3 different radio buttons, I'd like for the text input field that's above them to be populated with that radio button's value (ie: either "First Floor", "Second Floor", or "" .... nothing / clear the field).

I'd normally do this by using the text input field's unique ID attribute selector .. but these text input fields are being generated dynamically, so I'd prefer to just traverse the DOM somehow and to just populate the text input field that's above the radio buttons.

Also .. note that I need to implement this using jQuery's noconflict mode (which uses "jQuery" prefixes instead of "$").

Would someone here be so kind as to provide me with a Javascript function that would allow me to accomplish this?

Thanks!
- Yvan
0
Get 15 Days FREE Full-Featured Trial
LVL 1
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Team, I need some help diagnosing this issue, asked by one of our DBA's, server is part of a cluster, the cluster was manually failed over to the other node around the time this issue/error occurred?
errorSQL.png
Message
Login failed for user 'XXX\WINXXXX$'. Reason: Token-based server access validation failed with an infrastructure error. Check for previous errors. [CLIENT: XX.XXX.XX.XX] - Any ideas where/how I diagnose what the issue is here?

Many thanks
0
On this page: http://groupplanner.gallitin.com/flight/create?tripID=16&tripName=Cancun

I have a button to add flight and when clicked it clones the form as expected.  When I click any of the remove buttons it removes the entire form though.  How can I fix this?
0
We currently have a asp file with the following code:-

<%@ LANGUAGE=JSCRIPT %>
<%

// VARS TO CHANGE

var v1 = 12345;
var v2 = 12345678;
var targetFile = "mysecretpage.asp"

// END VARS TO CHANGE

var enterpriseName = targetFile.substr(0,targetFile.lastIndexOf("."));

function pad(num){
  return(num<10?"0"+num.toString():num.toString());
}

var now = new Date();

var key = pad(now.getUTCMinutes()) + pad(now.getUTCMonth()) + pad(now.getUTCDate()) + pad(now.getUTCHours());
key = (key * v1) - v2;

%>


<HTML><BODY onload="document.uptodate.submit();">

<form method="POST" action="http://uptodateonline.com/porthole/<%= targetFile %>" name="uptodate">
<input type="hidden" value="<%= enterpriseName %>" name="username">
<input type="hidden" value="<%= key %>" name="key">
<input type="submit" value="UpToDate">

</form>
</BODY></HTML>

Open in new window


I have amended the variables for security reasons.

I need to convert this code into a standard HTML file as server side scripting is disabled on our particular web server and we are unable to get it enabled.

My understanding is that this is simple Javascript so it should be possible to integrate this into a standard HTML page?

Any help would be appreciated as my experience with Javascript is minimal.
0
Hi,
Further to this
https://www.experts-exchange.com/questions/29042667/Add-button.html?anchor=a42220705¬ificationFollowed=192653361#a42220705

I adjust the column name in Javascript but the problem persists (I cannot delete the record), after re-deployment.
0
Production: https://www.fivetier.com/

I see I have 3 JS errors in console, but not having any luck trying to figure out what they are.  Wordpress seems to inject things, so hard to track down.  I've inherited the project so any suggestions?
0
Is there a piece of code I can put in a href which when you click the link shares the page in facebook or twitter?

I know you can use:

<a href="http://twitter.com/share?url=<URL>&text=<TEXT>via=<USERNAME>"><img src="tw-circle.png" border="0" height="36" width="36"></a>

But I want it to know the page it is on as it is for a page template.

Thanks,
0
I am using free fqgrid.  When user clicks a row, the selected row is displayed in a modal form to edit.  After record is submitted and saved, I can close the modal form in javascript, but I can't get the grid to reload ... it still displays the original row data.  I have tried removing the loadOnce = true (set it to false).

Any help appreciated.

Here is my javascript:
function Save(form) {
        var url = '/Dispatches/Edit';
        var formId = '#' + form.id;
        var frmData = $(formId).serialize();
        //alert(formId);

        $.ajax({
            type: "POST",
            url: url,
            data: frmData,
            success: function (response) {
                $('#myModal').modal('hide');
                $('#dispatchGrid').jqGrid.trigger('reloadGrid');
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //do your own thing  
                alert("fail");
            }
        });
    }

Open in new window


I should note that the updated row data saves fine.  This is a MVC 5 project.  Thanks in advance.
0
Hi, please need guidance on how to fix the npm error. Thanks so much in advance.

# rpm --query centos-release
centos-release-6-6.el6.centos.12.2.x86_64

Open in new window


# node --version
v0.10.48

Open in new window


# npm --version

module.js:340
    throw err;
          ^
Error: Cannot find module 'npmlog'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at /usr/lib/node_modules/npm/bin/npm-cli.js:18:11
    at Object.<anonymous> (/usr/lib/node_modules/npm/bin/npm-cli.js:86:3)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)

Open in new window

0
Using the documentation found here http://vinceg.github.io/twitter-bootstrap-wizard/ I have created a tabbed form wizard with Parsley validation.
JSFiddle here
I have the form validating perfectly when using the top tabs to move between tab-panes however I am having trouble with the "next" and "previous" buttons.
On initial click of the "Next" button on the first tab-pane the validation seems to work fine however this is where the trouble begins. The "next" button then renders itself "disabled" and does not work any more.
From what I can read the trouble begins on line 2 of my js. Line 3 (commented out) is my attempt at a fix but witht success.
Experts required.
N
0
PeopleSoft Has Never Been Easier
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Hello,

I am very new to nodejs but have been learning a lot these past few weeks.  I am trying to use passport to implement authentication but I am getting an error that I need to fix.  Any assistance would be much appreciated.  Here is the error I get..
node error
Below is part of my code:

index.js
const express = require('express');
const mongoose = require('mongoose');
const hbs = require('express-handlebars');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser')
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
var User = require('./models/account')

mongoose.connect('mongodb:cluster0-shard-00-00-yng8g.mongodb.net:27017,cluster0-shard-00-01-yng8g.mongodb.net:27017,cluster0-shard-00-02-yng8g.mongodb.net:27017/vendorCollection?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin');


app.use(cookieParser())
//Persists data in memory inside of application
app.use(require('express-session')({
    secret: 'vendorSecret',
    resave: false,
    saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())

//Allows you to use static files
app.use(express.static('public'))

app.use('/vendor', vendorRouter)
app.use('/admin', adminRouter)

passport.use( new LocalStrategy(User.authenticate()) )     //<---Error on this line
passport.serializeUser(User.serialize())
passport.deserializeUser(User.deserialize())

app.listen(3000, ()=>{
  console.log("Server Listening");
})

Open in new window

0
The following data is returned from my laravel coded controller:

data object
[{"id":1,"name":"View","createdDate":"2017-07-12 14:54:05","lastUpdate":"2017-11-07 13:52:27"},{"id":2,"name":"Read","createdDate":"2017-07-12 14:54:05","lastUpdate":"2017-11-07 13:52:27"},{"id":3,"name":"Write","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27"},{"id":4,"name":"Update","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27"}]

Open in new window


try object
[{"id":1,"name":"Dashboard","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","permission":[{"id":1,"name":"View","createdDate":"2017-07-12 14:54:05","lastUpdate":"2017-11-07 13:52:27","pivot":{"module_id_fk":1,"permission_id_fk":1}},{"id":3,"name":"Write","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","pivot":{"module_id_fk":1,"permission_id_fk":3}}]},{"id":2,"name":"Employee","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","permission":[{"id":3,"name":"Write","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","pivot":{"module_id_fk":2,"permission_id_fk":3}}]},{"id":3,"name":"Report","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","permission":[]},{"id":4,"name":"Access Right","createdDate":"2017-11-07 13:52:27","lastUpdate":"2017-11-07 13:52:27","permission":[]}]

Open in new window



In my angularjs controller I have the following line of code:

	$scope.compare = function(a,b){
		$scope.tmp = [];	
		for(var outer in a[0]){
			if(b.length>0){
				for(var inner in b){
					if(b[inner].name === a[0][outer].name){
						$scope.tmp.push({"name":a[0][outer].name,"status":true});
					}
				}
			}else{
				$scope.tmp.push({"name":a[0][outer].name,"status":false});
			}
		}
		return $scope.tmp;
	};

	$scope.init = function(){
		
		$scope.dfperm = [];
		$scope.modperm = [];
		$scope.counter = 0;
		
		$http({
			method: 'GET',
			url: "/api/v1/module/list"
		}).then(function successCallback(response){
			//console.log(response.data);
			//$scope.module = response.data;
			$array = response.data;				
						
			angular.forEach($array, function(outer, key) {			
				if(key==='data'){					
					$scope.dfperm.push(outer);
					//$scope.counter++;
				}
				if(key==='try'){
					angular.forEach(outer, function(outerItem, key){ 
						 var tmp = $scope.compare($scope.dfperm,outerItem.permission);
						 $scope.modperm.push({"name":outerItem.name,"permission":tmp});
					});
				}
			});
		}, function errorCallback(response) {
			console.log('intention error',response.data);
		});
		
	}

Open in new window


What I am attempting to do is to create a new permission object that has the status true or false.

As shown the data object contains a list of default permission.

The try object on the other hand shows that each module has permission. A module can have 0 or more than 1 permission.  

Now i'm trying to reconstruct the information so that each module has equal number of default permission but based on the try object conditioning (permission) is done to set the status either true or false.

However my code above doesn't do so. Rather a module with is set based on the try object conditioning (permission) and others are set with the default permission and status false.

Your help is kindly appreciated.
0
I'm working on responsive site which is using javascript to move elements around, but it is broken with Edge.
I examined the script and using the Emulation and punching in 1003px, the $(window).width()  function is returning 991px, but not on any other browser...?
Any ideas?
0
Refrencing form wizard here https://bootsnipp.com/snippets/featured/form-wizard-using-tabs

I'd like to modify the js in this wizard to add the class "complete" where the active of disabled currently reside.
Essentially an "li" tag will either contain disabled, active or complete.
Thanks in advance..
N
0
I intend to access the outer variable stated below

if(key==='data'){
	outer;  //outer variable
}

Open in new window


Inside the following like of code

angular.forEach(outer.permission, function(outer_perm, key) {	
        //I want to access outer
 });

Open in new window


here is the full line of code:

			angular.forEach($array, function(outer, key) {			
				if(key==='data'){
				    outer;
				}
				if(key==='try'){
					angular.forEach(outer, function(outer, key){
						 $module_name = outer.name; 
						 //console.log($module_name);
						 angular.forEach(outer.permission, function(outer_perm, key) {	
								//I want to access outer
						 });
					});
				}
			});

Open in new window


Your help is kindly appreciated.

Thank You.
0
Hi, I got this Multitrack Player to work on Node.js on a Node hosting service heroku.com
https://github.com/squallooo/MT5
I also got it to work locally on my PC.

I have Wordpress hosting at Dreamhost.

Now I want to include the Multitrack Player into the Wordpress page.
I need some help with that.

For a start, how can I simply 'insert' the player into my WP page?

Thanks.
0

JavaScript

120K

Solutions

41K

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.