jQuery

17K

Solutions

5K

Contributors

jQuery (Core) is a cross-browser JavaScript library that provides abstractions for common client-side tasks such as Document Object Model (DOM) traversal, DOM manipulation, event handling, animation and Ajax. jQuery also provides a platform to create plugins that extend jQuery's capabilities beyond those already provided by the library.

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

Sign up to Post

I would like to get the latitude and longitudes of an address from the OpenstreetMap Server. I use the following code:
The URI https://nominatim.openstreetmap.org/search/Keizersgracht%202,%20Amsterdam?format=json

gives me the following JSON output:

[
    {
        "place_id": 29597926,
        "licence": "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright",
        "osm_type": "node",
        "osm_id": 2729940028,
        "boundingbox": [
            "52.3654887",
            "52.3655887",
            "4.8878076",
            "4.8879076"
        ],
        "lat": "52.3655387",
        "lon": "4.8878576",
        "display_name": "489B-2, Keizersgracht, Grachtengordel, Amsterdam, Noord-Holland, Nederland, 1017DM, Nederland",
        "class": "place",
        "type": "house",
        "importance": 0.32100000000000006
    },
    {
        "place_id": 29345477,
        "licence": "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright",
        "osm_type": "node",
        "osm_id": 2722023917,
        "boundingbox": [
            "52.3669115",
            "52.3670115",
            "4.8842236",
            "4.8843236"
        ],
        "lat": "52.3669615",
        "lon": "4.8842736",
        "display_name": "460-2, Keizersgracht, Grachtengordel, Amsterdam, Noord-Holland, Nederland, 1016GE, Nederland",
        "class": "place",
        "type": "house",
        "importance": 0.32100000000000006
    },
    {
        "place_id": 

Open in new window

1
I have a select dropdown that is populated from a mysql table which is working great. The dropdown is on a update profile page so how do I populate the dropdown from one table but then also get the value that was stored in a different table and show it as selected in the dropdown.

Here is the code for the dropdown.
<select name="type" id="type" data-placeholder="type" class="form-control form-control-select2 select2-hidden-accessible" data-fouc="" tabindex="-1" aria-hidden="true" required>
													<option value="" selected>Type</option>
													<?php
													$type = $link->query( "SELECT * FROM type" );
													while ( $rows = $vertical->fetch_assoc() ) {
														$type = $rows[ 'type' ];
														echo "<option value ='$type'>$type</option>";
													}
													?>
												</select>

Open in new window

0
I am developing an app using Apache Cordova and I have the following code which fails to execute. The idea of the code is:

1) loop through the array with all orders (JSON)
2) retrieve the customer's name
3) generate a table or <tr>

The problem is point 2 - the code just stops and I have to restart the server.
The array with orders is not that big - around 150 JSON objects which I retrieve when the application loads;
the array with customers is even smaller: just two clients are in the array.

Is this an issue with JavaScript concurrency? I would appreciate it if someone can give me an idea of how to tackle this, as I have spent hours trying to figure out how to make this work.

Surely, it must be possible to retrieve the orders - then lookup the customer's name - and then put the data into another array.

Thanks

Massimo

      /**
       * @description retrieves all orders for megamax and genereates table rows for the HTML table
       */
      this.getAllMegamaxOrders = function () {
        "use strict";
        var mm_orderID = 0;
        var mm_customer_id = "0";
        var mm_orderDate = "";
        var mm_customerName = "";
        var mm_lat = "";
        var mm_lng = "";
        var mm_price = "";
      
        
        //loop through all orders from array allOrders
        for (i = 0; i < app.allOrders.length; i++) {

          //populate local variables
          mm_orderID = app.allOrders[i].id;
          mm_customer_id = 

Open in new window

1
I have a clock that is displayed on my website and I would like to display a different timezone depending on a variable from a database. If I have a user that lives in New York when I view his profile I want to display his current time. I have timezone as a field in the database for that user.

This is the code I'm currently using.
function GetClock(){
    var d=new Date();
    var nhour=d.getHours(),nmin=d.getMinutes(),ap;
    if(nhour==0){ap=" AM";nhour=12;}
    else if(nhour<12){ap=" AM";}
    else if(nhour==12){ap=" PM";}
    else if(nhour>12){ap=" PM";nhour-=12;}

    if(nmin<=9) nmin="0"+nmin;

    var clocktext=""+nhour+":"+nmin+" "+ap+" (MT) ";
    document.getElementById('local').innerHTML=clocktext;
}

GetClock();
setInterval(GetClock,1000);

Open in new window

-------------------

And then in the html I call it by
<span id="local"></span>

Open in new window

0
I have created the following two functions inside my JS file (which will be used in PhoneGap/Cordova) and I have put them outside of the main JavaScript class:

**
 *@description Returns the latitude of the current location
 *@return {float} a latitude
 */
function getLatitude() {
  return position.coords.latitude;
}

/**
 *@description Returns the longitude of the current location
 @return {float} a longitude
 */
function getLongitude() {
  return position.coords.longitude;
}

Open in new window


Why is it, that if I put this into my HTML page, I can get the coordinates - but when I call these functions from within JavaScript, I get an error saying that position is undefined?

What is a workaround so that I only get a latitude or longitude?
0
How do I post using jquery ajax?

I am having the issue that I get a wrong username and password error message from the server.
When I try using Postman, I don't have any problems connecting to a server and getting a value back.

I have to make use of .ajax because I have to make a synchronous call.

Am I missing something as part of the ajax POST message?

         * @description Places a new (empty) order for a customer. 
         *              If successful, the system will display a message
         *              informing the user that a number order has been
         *              placed (with the order ID)
         * @param {number} clientID the client's ID
         */
        this.placeNewOrder = function (clientID) {
      
          data = {
            OUCU: oucu,
            password: password,
            client_id: clientID,
            latitude: 41,
            longitude: 0
          };

          $.ajax(
            {
              method : 'POST',
              async : false,
              url : "http://137.108.92.9/openstack/api/orders",
              dataType : 'json',
               success: function (data) {
                        var obj = data;
                        if (obj.status == "success") {
                          //put new order ID into variable
                          newOrderID = (obj.data[0].id);
                          //get client's name and display it on the next page with the new order number
             

Open in new window

0
OK.  Unfortunately, my company uses Adobe Captivate for developing e-learning modules.  Captivate has no native dropdown element and the "widget" is sub-standard at best.  So, I am attempting to create my own dropdown that sizes itself to a Captivate "Smart Shape".  Basically, I want to 1) either replace the "Smart Shape" html at run time or 2) overlay the "Smart Shape" with my dropdown - I use the Smart Shape as a place holder in the slide.  I have been able to successfully accomplish (2).  The problem I run into is when a user resizes the Adobe captive Slide in their browser at run-time, the slide and all elements within the Slide - to include the Smart Shape resize and maintain their location on the slide; however, the custom dropdown I added remains the same.

I build the Captivate the project as HTML 5 vice .SWF, so the runtime code is HTML 5.  Also, it looks like Captive builds some of the HTML when the web application is started

So, how can I (1) stop Captivate from resizing the slide; or (2) how can I replace the "Smart Shape" with a dropdown element after building the web app so that it will resize if the slide is resized; or (3) how can I make the dropdown resize as the slide in resized?

NOTE:  The Smart Shape is Slide Resized:  Smart Shape us black and expanded while drop down remains the sameInitial Slide:  Dropdown overlays Smart Shapreblack
0
I am creating a Cordova app and I am using a single file. The application makes use of jQuery Mobile and I have created several sections inside the document using pages, like:

 <div data-role="page" id="addItems" style="background-color: white">

Open in new window


I created the following code in the JavaScript file:

function goToAddItems() {
  console.log('got to goToCards');
  $(':mobile-pagecontainer').pagecontainer('change', '#addItems');
}


/**
 * This is the main class
 */
var app = {

  //create initialize function:
  initialize: function () {
    document.addEventListener(
      "deviceready",
      this.onDeviceReady.bind(this),
      false
    );
  },

  // deviceready Event Handler
  onDeviceReady: function () {
    this.receivedEvent("deviceready");
  },

  // Update DOM on a Received Event
  receivedEvent: function (id) {
    
    $("#allWidgets").on("click", function (e) {
     this.goToAddItems();
      
    });

Open in new window


How do I programmatically

a) only display the home page when the app loads? and
b) how do change from one page to the other? I created the function goToAddItems()  -  but that doesn't seem to work.

Can anyone please guide me how this is done with the latest version of jQuery Mobile (1.4+)?

Thanks

Massimo

https://next.plnkr.co/edit/ru59CnaduxaqUyxbBvtI?p=preview&preview
0
Hi,

I have the following scripts included in my html file.
main.js file uses JQuery CDN, so JQuery CDN should come first. I understand that.
However, main.js also uses googleapis, but googleapis comes the last.
But I was told that this is okay because the last script tag includes "async defer"
So can anybody explain how async defer works here?


  <!-- JQuery CDN -->
  <script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>

  <!-- Local JS File -->
  <script src="js/main.js"></script>

  <!-- Google Maps -->
  <script src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXX" async defer></script>

Open in new window

1
This is the behavior I'm hoping to accomplish - is it possible?

Existing data is displayed when the page is first visited.  That link will allow toggling (works).
But if the New button is clicked, I want that to collapse (works).
Ideally, I'd rather if the New button was clicked a subsequent time, that it wouldn't open the Existing link - only collapse it when New isn't displayed so that New is the only card shown.
I also want that if Existing is clicked, that it will expand if collapsed...Currently, it does expand, but the title (span) disappears!. :(
I certainly don't want that, but I cannot see what is causing that.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>List Manager</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    />
    <link
      rel="stylesheet"
      href="https://use.fontawesome.com/releases/v5.8.2/css/all.css"
    />

    <style type="text/css">
      .jumbotron {
        padding: 2rem 1rem;
        background-color: #7d3f98 !important;
      }
    </style>
  </head>

  <body>
    <div class="row justify-content-center">
      <div class="col-8 mx-2 pt-4">
        <div class="jumbotron text-center">
          <h1 class="text-white">BD Manager</h1>
        </div>
      </div>
      <div class="col-3 pt-5">
        <button id="info" class="btn btn-warning 

Open in new window

0
Hello,

I have a Wordpress menu, it is a 3 level menu and the third level isn't working properly.

If you visit this link.
http://oalaca.nextmp.net/

Under the profession menu you will see What is Landscape Architecture, the next 3 menu items  ( Why is Landscape Architecture Important?, and  Studying Landscape Architecture only appear when  What Does a Landscape Architect Do) are supposed to only appear when you hover over What is Landscape Architecture?, but they display as default...  

Interesting thing, if I go and scroll over that item and and then scroll off, those 3 menu items close and everything works as it should.

So my question is
1. How do i make What Does a Landscape Architect Do?, Why is Landscape Architecture Important?, and  Studying Landscape Architecture only appear when  What Does a Landscape Architect Do is hovered over?
0
I'm developing a Cordova app and one of the function is, that it can display orders.
I would like to retrieve all the orders when the app starts and put them into a JavaScript array:


var allOrders = [];			
this.getAllOrders = function() {
				var url = "http://137.108.92.9/openstack/api/orders?OUCU=" + oucu + "&password=" + password;
				/* Get the data */

				$.get(url, function (data) {
					var obj = $.parseJSON(data); // 
					if (obj.status == "success") {
						// was able to get the data successfully 
						// loop through all orders
								$.each(obj.data, function(i, item) {
                  console.log(item);
									app.allOrders.push(item);
                });
          };
				})
      }

Open in new window


The JavaScript array is populated with JSON objects.

How do I read JSON objects out of the array? For example, I would like to find out in which position the Order ID 71415 is.

      //Searches for an order ID
      this.searchOrderID = function(OrderID) {
        ???
      }

Open in new window


I would appreciate it if someone could give me an idea how to read json objects out of a JavaScript array. Searching for an order ID is one thing and then I would like to retrieve the picture URL for example .. I think once I know how to loop through the variable and then read the element ID, it should make it easier for me to implement the other functions.

Thanks for your help

Massimo
JSfiddle: https://jsfiddle.net/mscola75/ksqyem7g/2/



The JavaScript array with data
0
Looking for a jQuery based date calendar widget that can be tied to a text box on a form. I am using https://api.jqueryui.com/datepicker/

It either lacks the functionality to prevent user from typing in gibberish as a date or I don't know how to configure it properly. I tried this:

$(function() {
            $("#datepickertd").datepicker({
			constrainInput: true}););
        });

Open in new window


I thought constrain input required a format mm/dd/yy (or whatever you pick as the default format). Constructed as in the code, it disables the functionality totally.

Happy with a fix for this or suggestion for another one that has this feature.

Thanks
0
I would like to write a function that returns all orders and puts the OrderIDs in a JavaScript array.

The JSON looks like this:

{
    "status": "success",
    "data": [
        {
            "id": "69507",
            "client_id": "1",
            "date": "2019-05-18 11:02:20",
            "latitude": "0.00000000",
            "longitude": "0.00000000"
        },
        {
            "id": "69514",
            "client_id": "2",
            "date": "2019-05-18 11:15:20",
            "latitude": "0.00000000",
            "longitude": "0.00000000"
        },
        {
            "id": "69513",
            "client_id": "1",
            "date": "2019-05-18 11:15:16",
            "latitude": "0.00000000",
            "longitude": "0.00000000"
        },
        {
            "id": "69511",
            "client_id": "1",
            "date": "2019-05-18 11:13:23",
            "latitude": "0.00000000",
            "longitude": "0.00000000"
        },
        {
            "id": "69510",
            "client_id": "1",
            "date": "2019-05-18 11:12:01",
            "latitude": "0.00000000",
            "longitude": "0.00000000"
        },
        {
            "id": "71397",
            "client_id": "1",
            "date": "2019-05-20 22:33:36",
            "latitude": "41.00000000",
            "longitude": "0.00000000"
        }
    ]
}

Open in new window


As I'm using jQuery, I use the following method to loop through the array - and then get the "id":

var orderIDs = [];

function getAllOrderIDs() {
  var url = "http://137.108.92.9/openstack/api/orders?OUCU=" + oucu + "&password=" + password;
  /* Get the data */
  $.get(url, function (data) {
    var obj = $.parseJSON(data);
    if (obj.status == "success") {
      // was able to get the data successfully 
      // loop through all orders
      data = $.parseJSON(data);
        $.each(data, function(i, item) {
          //alert(item);
          orderIDs.push(data[item].id);
        });
    };
  })
}

Open in new window


I get the following error message:
index.js:49 Uncaught TypeError: Cannot read property 'id' of undefined

Line 49 is the line of code which I puts the orderID into the array.

Can someone please give me a clue what I'm doing wrong?

Thanks for your help

Massimo
0
I have a Asp.net MVC app which sends a float array data to the client

float[320,240]
See attached for the data, its around 1.4mb

I need to dramatically reduce this size, and be able to convert it to the current format in Javascript

Here is the request
 $.ajax({
  type: "POST",
  url: "@Url.Action("CameraChange", "Home")",
  async:true,
  data: "{'cameraId':'" + ID + "'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (response) {
                 imageTemperatureDataArray = JSON.parse(response.TemperatureDataArray);
  },
   error: function (e) {
       alert("error: " + e.message + ' ');
  }
 });

Open in new window


Then I use it futher down in
 
  $("img#schemesImageSchemes").mousemove(function (e) {
       $('#dataSchemes').text(imageTemperatureDataArray[myX][myY]);
});

Open in new window


Is there a way to reduce this size of the attached
And how would i then convert it in JS ?
floattemparray.txt
0
Hi,

I wanted to show and hide div based on condition in jquery

Below code works and hide all div's having class "countryselection"
$(".countryselection").hide();

Open in new window


But if I am passing variable at runtime and show all div's like below:
$(selectedValue).show();

Open in new window


but it doesn't work.

Below is the code snippet. Class in variable "selectedValue" is already applied in the div.

Please advise.
var selectedValue = jQuery(this).val();
$(".countryselection").hide();

alert('vcountry: ' + selectedValue);
$(selectedValue).show();

Open in new window


Regards,
0
I have tiles that I am loading in a repeater using VB.net.
TileExample.PNG
For each tile, when they hover over the percentage I want to display a tag that is a button.
TileExampleHover.PNG
I want to use Jquery to do this, but I also want to make sure that it's displaying the 'View More' tag that is tied to the corresponding percentage label. Is this possible?

This is my code. I simplified the table so it wouldn't have all the fields. It just has the fields that are concerned with my question.
<table id="TableTraining" class="display scrollTable cards" style="width: 100%; text-align: left !important; font-size: 14px;">
            <thead>
                <tr class="colorFontRTOBlue" style="font-size: 12px;">
                    <th class="">Percentage
                    </th>
                </tr>
            </thead>
            <tbody id="dataContainer" clientidmode="Static" runat="server">
                <asp:Repeater ID="repRepeater" runat="server">
                    <ItemTemplate>
                        <tr id="row" class="<%# Eval("divRowClass").ToString()%>" style="cursor: pointer;">
                            <td class="stylRow5Perc stylTileLabel stylTileActive stylActivePercent">
                                <asp:Label ID="lblActiveStatus" Text='<%# Eval("ActiveStatus").ToString()%>' runat="server"></asp:Label>
                                <asp:Label ID="lblPercentageTile" Text='<%# Eval("Percentage").ToString()%>' 

Open in new window

0
I recently upgraded from jQuery 1.11.1 to jQuery 3.0.0 and now  a simple change on a couple of radio buttons no longer works. How can I get this back to working as it should?

    <script type="text/javascript">
       jQuery(document).ready(function () {
            j$('#cmdCreateNewEvent').prop('disabled', 'disabled');

            $('#rdoSameDonor').change(function () {
                EnableCreateButton();
            });
            $('#rdoDifferentDonor').change(function () {
                EnableCreateButton();
            });
        });

        function EnableCreateButton() {
            $('#cmdCreateNewEvent').removeProp('disabled');
        }
    </script>

Open in new window

0
I have a classic ASP page that pulls dates from the database. These dates are dates that my jquery calendar must disable.

I need a page that takes information from the database and puts it into an array which is then put into the javascript.

In order to disable specific dates, we need to create a custom function. Our function will compare all the dates with an array of disabled dates.

So if a date is in disabled dates array our function will simply return false.  Here is the code snippet. The code is heavily commented and will help you in understanding.


Here is the Javascript for Jquery Datepicker

 <script>
 
 /** Days to be disabled as an array */
var disableddates = ["12-3-2019", "12-11-2019", "12-25-2019", "12-20-2019"];
 
function DisableSpecificDates(date) {
 
 var m = date.getMonth();
 var d = date.getDate();
 var y = date.getFullYear();
 
 // First convert the date in to the mm-dd-yyyy format 
 // Take note that we will increment the month count by 1 
 var currentdate = (m + 1) + '-' + d + '-' + y ;
 
  // We will now check if the date belongs to disableddates array 
 for (var i = 0; i < disableddates.length; i++) {
 
 // Now check if the current date is in disabled dates array. 
 if ($.inArray(currentdate, disableddates) != -1 ) {
 return [false];
 }
 }
 
}
 
 
 $(function() {
 $( "#datepicker" ).datepicker({
 beforeShowDay: DisableSpecificDates
 });
 });
 </script>

Open in new window

The inArray() method returns -1 if  it cannot find a match.


SQL Database of Dates
tbl_calendardates

/****** Object:  Table [dbo].[tbl_calendardates]    Script Date: 5/15/2019 11:30:35 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[tbl_calendardates](
	[autoid] [int] IDENTITY(1,1) NOT NULL,
	[daterequired] [datetime] NULL
) ON [PRIMARY]
GO

Open in new window



Thank you in advance
0
Hi there,

I have an issue with my woocommerce mini cart.

The issue I have is that there are a few items that seem to be stuck in the cart no matter if you are logged in or not. If you try and remove them, a few seconds later they appear again.

I thought It might have been outdated plugins and template files, so I have backed up my site and updated everything along with all the template files, still the same issue.

My website is www.ingeniousgifts.co.uk and you can access the slide out mini cart from the top right of the screen.

I have attached a screen record so you can see what happens.

I would really appreciate if someone could help me find out why this is happening and how to fix it?
Home---Ingenious-Gifts.webm
0
Anybody here who can give me a hint to execute custom Javascript inside a CodeceptJS script?
I need to close a layered window and I currently cannot do it with codeceptJS default calls, so I want to close it with jQuery.
I use
	I.executeScript(function() {
		$('#Sidemenu').hide();
	});

Open in new window

Inside my test, but I only get the error message that $ is not defined.
0
I need to send a simple javascript / jQuery alert message from my controller in MVC5. How do I do this? I have the code below in place, but the alert is not firing, nothing happens when the line of code with the script in it is hit.

				if (manager.AddedServicesList == null)
				{
					Response.Write("<script>alert('NO SERVICES ADDED');</script>");
					return RedirectToAction("Category", manager);
				}
				else
					return RedirectToAction("GroupDetails", manager);

Open in new window


This works, but then I just get a blank page. I need to get back to/stay on/in the view where I'm currently at.

return Content("<script language='javascript' type='text/javascript'>alert('Hello world!');</script>");

Open in new window

0
Hello,
Can someone please suggest how to convert date like below to ticks
May 09 2019 23:59:59 to ticks in jquery or javascript?

Correct ticks conversion value should be :

636930431999990000

As per this link:
https://tickstodatetime.azurewebsites.net/

Thanks.
0
  function getContacts(listId, cOnly) {

            if (typeof contactTable !== 'undefined')
                contactTable.destroy();
            contactTable = $('#contactstable').DataTable({
                "serverSide": true,
                "stateSave": true,
                "ordering": false,
                "searching": true,
                "oSearch": {"bSmart": false},
                "searchDelay": 1500,
                "ajax": {
                    "url": "get-contacts.php",
                    "type": "POST",
                    "data": {
                        listId: listId,
                        co: cOnly
                    }
                },
                "rowCallback": function (row, data) {
                },
                "initComplete": function (data) {
         
                },
                "columns": [
                    {"data": "contact"},
                    {"data": "email"},
                    {"data": "company"},
                    {"data": "date"},
                    {"data": "actions"}
                ],
                'columnDefs'        : [      
                { 
                    'searchable'    : false, 
                    'targets'       : [2,3,4] 
                }
            ],
                "order": [[0, 'desc']]
            });


     
        }

Open in new window



so this function creates my dataTable,

all works table it up, i only perform search functions on contact and email,

how ever it is failing to give me exact results , for example first record is  Tim Smith , i can clearly see Tim Smith, i type Tim Smith into the search input provided by data-tables, and he isnt shown in the result ?

https://datatables.net/
0
I am using Jquery Datatable.
If anyone can please suggest ,why i am getting blue underline only in Internet Explorer Edge browser for some random dates only like below image: Please suggest thanks.

Please see below image:

Automatic blue underline only in Internet Explorer Edge browser
0

jQuery

17K

Solutions

5K

Contributors

jQuery (Core) is a cross-browser JavaScript library that provides abstractions for common client-side tasks such as Document Object Model (DOM) traversal, DOM manipulation, event handling, animation and Ajax. jQuery also provides a platform to create plugins that extend jQuery's capabilities beyond those already provided by the library.

Related Topics