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,
 I am working on custom pagination where i need to calculate the total pages to help with Total count and Rawlimit variable. I am using some manually code. Can you please help me to update my code to calculate Total number of pages?

      var totalItems = 1200;
      var RawLimit = 30;
     
    var totalPages = (totalItems /RawLimit) +1;  // Mod function  

Open in new window

1
Experts,
  I have one js file for dynamic pagination. We did not use any plug in for this code. I would like to implement functionality with css.

  1. Highlight the Active page
  2. Disable the Previous page if we  are one first page.
  3.  Disable the Next Page if we are on last page
 
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
   (function () {
var overrideCtx = {};
overrideCtx.Templates = {};
overrideCtx.Templates.Footer = pagingControl;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
})();

 function pagingControl(ctx) 
 {
    var firstRow = ctx.ListData.FirstRow;
    var lastRow = ctx.ListData.LastRow;
    var prev = ctx.ListData.PrevHref;
    var next = ctx.ListData.NextHref;
    var view = ctx.view;
    var filter = ctx.ListData.FilterLink;
    view =  view.replace(/[{}]/g, "");
console.log(view);
    var totalItems = $('tr#aggWPQ2 td.ms-vb2 b').html();
        totalItems = Number(totalItems.replace('Count=&nbsp;', '') );
    var totalPages = (totalItems / 5) +1;  // Mod function 
	
	
	// "?Paged=TRUE&p_ID=10&PageFirstRow=11&View=f0e50c0f-5f49-46f0-890d-fb6039528edd"

  var html = "";
		 
          html +="<div class='Paging'>";
          html += prev ? "<a href='" + prev + "'><span><&nbsp;Previous Page</span></a>" : "<a href='" + prev + "'>Previous Page</a>";
	
          var pageID =  0;
          var pageFirstRow = pageID + 1;
        

Open in new window

1
I have a web page that has a date input field. This is in html 5. I need a jquery or javascript option to check if a data has been supplied, else add the default date "01/02/1901". This would be an event triggered by the submit button. I just need to update the field before the post.

<input type="date" name="Date Worked" id="add_Date_Worked" />
<input type="submit" value="Save Changes" />

Open in new window

1
I am creating a piece of javascript to show an opt-in field only if a specific country is chosen on a form AND the email address is not a public email address.  It checkes to see if the email @ is not a specific email extension and the country.

So if I choose The United Kingdom (which passes)  and fill in an email address of info@MYWEBSITE.com, the info@MYWEBSITE.com fails.  Below in the code it alerts "Stage Nine"  Which should indicate that my domain is not on the list (country_list).  

So somewhere between line 60 and line 75 it fails and/or I have something wrong in my code.  Any insight will be helpful. (optin function)

<script>
$(document).ready(function() {
    MktoForms2.whenRendered(function(mform) {
  var varIsDeclared = true; 

  if (domain_list.length == 1) {
    domain_list = "@gmail.com; @yahoo.com; @hotmail.com".split(";");
  }
  if (country_list.length == 1) {
    country_list = "Austria;Italy;Belgium;Latvia;Bulgaria;Lithuania;Croatia;Luxembourg;Cyprus;Malta;Czechia;Netherlands;Denmark;Poland;Estonia;Portugal;Finland;Romania;France;Slovakia;Germany;Slovenia;Greece;Spain;Hungary;Sweden;Ireland;United Kingdom".split(";");
  }


  try{ mktoPreFillFields; }
  catch(e) {
      if(e.name == "ReferenceError") {
          varIsDeclared = false;
      }
  }

  $('#Country').change(function(){
      
    if ($('#Country').val() != 'United States') {
        
      if (varIsDeclared) {
        if (!$('#GDPR_Opt_In__c').is(':checked')) {
            

Open in new window

0
I am used to php/mysql where I would just join tables but mongoose seems to be a whole other beast.

I have a product schema and a user schema.

here is product:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const productSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    category: {
        type: String,
        required: true
    },
    image: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    userId: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    address: {
        city: {type: String, required: true }
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
});

module.exports = mongoose.model('Product', productSchema);

Open in new window


And the user:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    firstName: {
        type: String,
        required: true
    },
    lastName:  {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        index: true,
        unique: true
    },
    contactNo: {
        type: String,
        required: true
    },
    password:  {
        type: String,
        required: true
    },
    address: {
        city: {type: String, required: true },
    }
});

module.exports = mongoose.model('User', userSchema);

Open in new window


When I as the admin user want to see the users first name and last name for the added product (as well as that product informatioN) I would to 'join' the 'tables' and based on the UserID in the product schema get the first name and last name from the users schema.

I am trying to use .populate here but not sure if it's correct or efficient.

exports.getApprove = (req, res, next) => {
    const productId = req.params.productId;
    Product.findById(productId)
    .populate('userId', 'firstName', 'lastName')
    .then(product => {
        res.render('account/approve', {
            pageTitle: 'Approve Listing',
            path: '/accounts/approve',
            product: product
        });
    })
    .catch(err => {
        console.log(err);
    });
};

Open in new window


console.log(product.userId.firstName);

Open in new window


Just wondering if I am not meant to use .exec() or .execPopulate() here
0
How do you make your npm package which includes an index.html page and a few folders of css and and javascript files launch a web page after you type "npm start" in the console window?
0
Hi there!

I want to reproduce EXACTLY this fiddler : https://jsfiddle.net/0Lng89tq/5/ 
(Please don´t ask my reasons to do it, nor tell me that modals were not created to be used like that, etc.)

To do so (that is, to reproduce that fiddler), I have created two files:

(A) JS file named modal_background.js with exactly the following content:

------------------------------------------------------
$(document).ready(function(){
$('#myModal').modal();

$('#myModal').on('shown.bs.modal', function() {
    $(document).off('focusin.modal');
});

$('.swal').click(function() {
      swal({title:'Test', input: 'text'});
});
});
------------------------------------------------------


(B) HTML file named fiddler_modal.html with exactly the following content:

------------------------------------------------------
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/modal_background.js"></script>

<meta charset="utf-8">
    <!-- Stylesheets-->
    <link rel="stylesheet" href="css/bootstrap.min.css">

<title>Untitled Document</title>
</head>
<body>

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<button type="button" class="swal">
swal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" …
0
I have an MVC C# Web application. I need a way to check a cookie name ="User_Role", if it = "UR500" then hide a menu object which is included in the layout.cshtml. Where would I place this script?
1
I have an MVC C# web application. I am trying to force a user choose from a drop down; in turn that selection is then used as a parameter to in another dropdown. I have a series of these activities. My first drop down does exactly correct, user chooses a selection, the selection is captured and the controller returns the new list and the user is asked to choose from the second list. My problem is that I cant seem to get the third drop down to get the last selection. I can see the controller is returning the data correctly, but I have something not quite right in the code. Maybe I have a variable or something that is keeping previous values. See my code snips below:

       window.onload = function () {
            document.getElementById("add_Date_Worked").setAttribute("readonly", "readonly");
            document.getElementById("add_Client_ID").onchange = function () {
                if (this.selectedIndex !== 0) {
                    document.getElementById("add_Product_ID").removeAttribute("disabled");

                    /* Client ID Drop Down Parameter Selection Start */
                    $.getJSON("../Home/GetFilteredProducts", { id: jQuery("#add_Client_ID").val() },
                        function (data) {
                            var select = $("#add_Product_ID");
                            select.empty();
                            select.append($('<option/>', {
                                value: 0,
                                text: "Select 

Open in new window

1
I'm going through a Udemy course on the MERN stack. Totally new territory for me and I've come across something that doesn't throw an error, but it's different from what should be on my screen according to the course.

Here's my code in my server.js file:

const express = require("express");

const app = express();

app.get("/", (req, res) => res.send("Hello"));

const port = process.env.PORT || 5000;

app.listen(port, () => console.log("Server running on port ${port}"));

Open in new window


When I do this on GIT Bash terminal:

$ node server

I get this in response:

Server running on port ${port}

According to the course, I should be getting:

Server running on port 5000.

There are no errors and if I go out to localhost:5000, I see "Hello," but the fact that I'm getting "{port}" instead of "5000" bothers me.

What am I missing?
1
I am working with pagespeed and gtmetrix and they both say I need to defer this script - https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js 

As you can see in the plugin async javascript I have this listed to defer

https://gyazo.com/6d3ba7273cb4256ebb7a3eed49d9cb6d

However, looking at the source at https://www.theherbsplace.com/product/artemisia_combination_p_163/?loggedout=true you can see that the script isn't being deferred.  

Here is the gtmetrix readout - https://gyazo.com/533542c729b4e15b20cc0f5ca9799bb1

How do I get this script to defer?  Is there another method that is better?

Thanks,
0
I am using a 3rd party script to upload images via Ajax and the callback gives you an array with the details of each uploaded image like the name, size, etc. I want to store the name of the images in the database.

I tried this but it only inserts the first image name:

        if (data.isSuccess) {
         const uploaded = uploader.getFileList();
         for (const images of uploaded) {
            console.log(images.name);
            const upload = new uploadModel({
                imgName: images.name
            });
            return upload.save();
         }

Open in new window


If I just console.log it however, it lists all the image names.
1
I have a web application that is using html 5. I need to check a date input field to see if it has a value, if not, then add then add the date: (1901-01-01) yyyy-MM-dd. I would like to use javascript. The input date field is below.

html code ----------------------------------------------------------------------
<input type="date" name="Date_First_Use" id="add_Date_First_Use" class="form-control" disabled />

Open in new window

1
I have an image which is 320x240 px

I have an array of values for each pixel in the image (76,800 points)

If the user hovers over any part of the image I need to look at the array and return the corresponding value for it.

i.e.
X Y position [0,0] of the image = the first value in the array.

If I wanted to find out the X Y position [65,33] of the image, and then look up the  value in the array, what would be the correct forumla to do this
1
I have an MVC C# web application and having issues capturing a date input field value. For some reason, even though the user selects a date from the date picker, the value passed to the control is always the same not sure why. Maybe I have an issue with my code. See code and screen shot of the values below.

cshtmel ------------------------------------------------------
<input type="date" name="Date Worked" id="add_Date_Worked" class="form-control" disabled required />

Open in new window



Controller ---------------------------------------------------
 [HttpPost]
        [ActionName("AddTimeInfo")]
        public ActionResult AddTimeInfoPost(TimeInfo timeinfo, string birthdate)
        {
            if (ModelState.IsValid)
            {
                timeinfo.Date_Worked = DateTime.Parse(string.Format("{0:yyyy-MM-dd}", timeinfo.Date_Worked));                
                try
                {
                    timeinfoDao.InsertTimeInfo(timeinfo);
                    TempData["Success"] = "true";
                }
                catch (Exception e)
                {
                    TempData["Success"] = "false";
                }
            }
            else
            {
                var errors2 = ModelState
                    .Where(x => x.Value.Errors.Count > 0)
                    .Select(x => new { x.Key, x.Value.Errors })
                    .ToArray();
                TempData["Success"] = "false";
            }
            return RedirectToAction("TimeInfo", "Home");
        }

Open in new window

1
I use HTML5 and JS.
I use Bootstrap modal for pop-up.
The modal works on clicks,

How can I show it when page loads. ( without clicking )
this is the script that I use
<script>
$('#myModal').on('shown.bs.modal', function () {
  $('#myInput').trigger('focus')
})
</script>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Open in new window

1
Turn off scrolling and zooming when drawing on image with touch screen (ie: phones and tablets)

I have a webpage designed for the user to draw on an image. When the user moves their finger across the image on a touch screen, especially when zoomed in, the page scrolls instead of drawing on the image.  How do I turn off scrolling and zooming when the user draws on the image?

Here is a link to the webpage modified so it doesn't send data to me: www.barnwellmd.com/PainDiagram/Testdrawing.html.

Here is the code:
/* © 2009 ROBO Design
 * http://www.robodesign.ro
 */

var imageData, context, pixels;

function clearCanvas()
{
	context.putImageData(imageData, 0, 0);
}

function checkFields()
{
	var themessage = "Please complete the following fields:";
	if (document.form.ptname.value=="") 
		{
		themessage = themessage + "\n     Patient's Name";
		}
	if (document.form.dob.value=="") 
		{
		themessage = themessage + "\n     Birthdate";
		}
	//alert if fields are empty and cancel form submit
	if (themessage != "Please complete the following fields:") 
		{
			alert(themessage);
			return true;
		}
		else
		{
			return checkdate(document.form.dob.value);
		}
}
function checkdate(input)
{
	
	var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
	var returnval=true
	if (!validformat.test(input))
		alert("Invalid Date Format. Format: (mm/dd/yyyy) \nPlease correct and submit again.")
	else
	{ //Detailed check for valid date ranges
		var 

Open in new window

0
I have an MVC C# Web Application and need to enable a second input selector when another selector has a value. I have included my Javascript & input selectors. I keep getting the error: Cannot set property 'onchange' of null. When user makes a selection and it is not the "Select a Client" option, then enable the input selector "add_Product_ID"

JavaScript ------------------------------------
    <script type="text/javascript">
        document.getElementById("add_Client_ID").onchange = function() {
            document.getElementById("add_Product_ID").setAttribute("disabled", "disabled");
            if (this.selectedIndex !== 0)
                document.getElementById("add_Product_ID").removeAttribute("disabled");
        };
    </script>

Open in new window


HTML -----------------------------------------
            <div class="row mg-t-20">
                <label class="col-sm-5 form-control-label">Client:</label>
                <div class="col-sm-6 mg-t-10 mg-sm-t-0">
                    <select name="Client_ID" id="add_Client_ID" class="form-control" required>
                        <option value="0">Select a Client</option>
                        @{
                            foreach (Client client in Model.Clients)
                            {
                                <option value="@client.Client_ID">@client.Client_Name</option>
                            }
                        }
                    </select>
                </div>
               

Open in new window

1
I have an input field that requires a user to enter time in a decimal form of hours + minutes. I need an html validation regex that will force a user to only enter the decimal 0 or 5. For example, user can enter the following valid numbers: (10.0; 10.5; 11.0; 3.5; 2.0) and so on. Invalid numbers:( 10.1; 10.2; 10.4; 3.2; 4.4;7.7). I just need to ensure user enters .0 or .5 decimal  no greater than 99.5, and great than 0.
1
I have an MVC C# Web Application and need to add some javascript to a partial view. I cannot seem to get the partial view to recognize the javascript. Every time I run the partial view in google dev, I get the error "cannot find the function". How can I include javascript in a partial view?
1
I have an issue where select B (dropdown) which is hidden until a specific value is selected in select A. The weird thing is my event listener on  select B breaks/stops working when it becomes visible. The form maintains the state of the selects so If select A has the value which makes select B visible then if I reload the page and select B is visible on page load, everything works. I'm not sure how I get the event listener to work when hidden and then becomes visible?  Is this a common issue?  I tried only attaching the listener once visible but that still didn't work.
0
Is Jquery outdated? what's the new technology that has replaced JQuery? Is it Bootstrap, Angular or React?

FYI, I don't have enough knowledge on Bootstrap, Angular or Reactjs hence am trying to determine what is the latest that I should be using on newer web applications.

Thanks for the info.
1
I have an MVC C# Web Application and have a text area input field that needs to be hidden when the page loads. I also have a drop down input field that a user picks a value from the drop down list. What I'm trying to do is if the user selects "Free Text" option with a value of "55" from (add_Time_Description_ID) input, the div area (divTimeNotes) becomes visible. So...this div area will toggle hidden/unhide based on the drop down selection. If page loads and the drop down does not = 55, div is hidden. I'd like to do this with Javascript but am having issues accomplishing. Can someone assist. See input names below:

                <div class="row mg-t-20">
                    <label class="col-sm-5 form-control-label">Time Description:</label>
                    <div class="col-sm-6 mg-t-10 mg-sm-t-0">
                        <select name="Time_Description_ID" id="add_Time_Description_ID" class="form-control" required>
                            <option value="">Select a Time Description</option>
                            @{
                                foreach (TimeDescription timeDescription in Model.TimeDescriptions)
                                {
                                    <option value="@timeDescription.Time_Description_ID">@timeDescription.Time_Name</option>
                                }
                            }
                        </select>
                    </div>
                    <label class="col-sm-1 …
1
I have a form for adding a product which lets a user input product name, description etc. and also allows an image upload.

In my app.js file which is my entry point, I have:

const fileStorage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, 'uploads');
    },
    filename: (req, file, cb) => {
       cb(null, new Date().toISOString() + '-' + file.originalname);
    }
  });


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

app.use(multer({ storage: fileStorage , fileFilter: fileFilter, limits: { fileSize: 100000} }).single('image'));

Open in new window


Here is my controller:

exports.postAddListing = (req, res, next) => {
    const title = req.body.title;
    const category = req.body.category;
    const description = req.body.description;
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(422).render('account/add-listing', {
            pageTitle: 'Add Item',
            path: '/account/add-listing',
            errorMessage: errors.array(),
            successMessage: null,
            oldInput: {
                title: title,
                description: description
            }
        });
    }

    const image = req.file;
    const imageUrl = image.path;

    const product = new Product({
        title: title,
        category: category,
        description: description,
        userId: req.user,
        datePosted: Date.now(),
        imageUrl: imageUrl
    });
    product.save()
    .then(result => {
        const successMessage = req.flash('success', 'Item sucessfully added');
        res.redirect('/account/add-listing');
    })
    .catch(err => console.log(err));
};

Open in new window


I am using express-validator for form validation. The problem I have is that if I for example leave all fields empty but choose an image, validation will fire and I will get error messages but the image will still upload. If form validation fails I don't want the image to upload but not sure how to achieve that.
0
Hello everyone,

I'm trying to give an extra use to a JS function that is originally included in a handler file that ame with a template. It handles the Date Range Picker JavaScript program. The function is included in the forms-plugins.js file, and has a var handleDateRangePicker that handles all the options for that script. It fills the dropdown with a standard range of dates, then opens a dropdown menu when the user clicks on it, the user selects a new range of dates and hit "Apply". The dropdown closes and the new range is displayed in the select field.

What I want is to interact with that (both the default range of dates and the new selected range of dates). The problem is that onChange event doesn't do the trick. If I include some "alert" code inside the plugins file, it works flawlessly but, how do I pass those variables to the php file so I can fiddle with them the way I want? Here's the shor version of the handler for that script in the forms-plugins.js file:
var handleDateRangePicker = function() {
	
	var today = new Date();
	var dd = today.getDate();
	var mm = today.getMonth() + 1; //January is 0!

	var yyyy = today.getFullYear();
	if (dd < 10) {
	  dd = '0' + dd;
	} 
	if (mm < 10) {
	  mm = '0' + mm;
	} 
	var today = dd + '/' + mm + '/' + yyyy;

	$('#advance-daterange span').html(moment().subtract('days', 29).format('DD/MM/YYYY') + ' - ' + moment().format('DD/MM/YYYY'));

	$('#advance-daterange').daterangepicker({
		format: 'DD/MM/YYYY',

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.