/r/jquery

Photograph via snooOG

News, articles, plugins and tutorials for jQuery, the world's most popular Javascript library! Covering jQuery Core, jQuery UI, jQuery Mobile, and other related projects.

News, articles, plugins and tutorials, covering jQuery Core, jQuery UI, jQuery Mobile, and other related projects.

Smokey says: install solar panels to fight climate change! [see more tips]

Resources:

Other subreddits you may like:

Does this sidebar need an addition or correction? Tell us here

/r/jquery

20,709 Subscribers

1

When using Jquery how does Javascript actually handle the GET or POST? I mean I understand that in an HTML file the Javascript sends a get or post with $.get( or, $.post(, but, the file that receives it, how does that work? I mean how does it actually handle the get or post and process it?

get or post in jquery?

7 Comments
2024/04/10
18:06 UTC

1

Nested API call returns error

I am developing a website for school and we need to use vue js and jQuery. So I have tried to make nest two api calls since I am using the data of the first one to call the second one, and it returns an error 404 specifically on the second api. I have tried separating the api calls and have them be different buttons and everything works perfectly fine. I want to combine them in order to only have to use one button but I do not understand why I keep getting the error only in that specific situation.

3 Comments
2024/04/05
01:40 UTC

1

Best way to make a single page application with jQuery and PHP?

I'm developing a website for school and I need to use vanilla jQuery, PHP and Bootstrap but I need help with the navigation (I've never used jQuery or PHP until now). In the main layout I have a navbar with a bunch of sections but I want to replace the content of the main div without reloading the page, I've done routing in React and Svelte but I'm finding very different approaches for what I'm trying to achieve.

https://preview.redd.it/3i9ndsmux5sc1.png?width=1032&format=png&auto=webp&s=dfe39591174cc1b71bc5d53133154d1a7a43417a

3 Comments
2024/04/03
01:58 UTC

2

unable to get contents of html file and display in web page div using $.get()

I am new to jQuery. Using it and Bootstrap and amazed at what I was able to put together very quickly with limited knowledge.

I have a site running on IIS, index.html is in docroot and has a navbar and container. On Load, jQuery loads a file called pipeline.html into the container. When a user clicks a link on the navbar called Clients, a page called Clients.html is loaded in the container (replacing pipeline.html). Clients.html has a button that opens a modal and another container of its own. When a user clicks the button and the modal opens, the user can enter data in the modal. When the user is done entering data they click add. At this point what I would like to have happen is to merge the user-entered data with the html contents of another file called newclient.html replacing the text values for the DOM elements with ID attributes of the same name as the input names of the Modal. (e.g. client name, client id, etc). Once merged, I would load the modified html content into the container div of clients.html.

I'm stuck here:

function addNewClient() { 
	var clientID = $('[aria-label="ClientID"]').val();
	var clientName = $('[aria-label="ClientName"]').val();
	var kickoff = $('[aria-label="ClarityID"]').val();
	var goLive = $('[aria-label="GoLive"]').val();
	var duration = $('[aria-label="Duration"]').val();
	var branches = $('[aria-label="Branches"]').val();
	var employees = $('[aria-label="Employees"]').val();
	var accounts = $('[aria-label="Accounts"]').val();
	var assets = $('[aria-label="Assets"]').val();
	var client = clientName + " (" + clientID + ") ";
	$('#client_list').text('');
	
	$.get('./views/newclient.html', function(data) {
		var html = $(data);
		alert( $(html) );
    });

This returns [object Object]. When I output $(html).Text, the text is displayed without any of the html markup. The target div/container has ID='client_list'. At this point I can't even get alert to display the html content of newclient.html unmodified. Can you guys help me out with what I am doing wrong?

1 Comment
2024/03/28
23:24 UTC

4

First time publishing a jqeury plugin.

Sooo, I published my first npm package: https://npmjs.com/package/@uzbeki/jquery-gantt-chart

Backstory: I needed a jqeury plugin for creating a gantt chart. The one I found was old and laggy, not updated in a while. So I forked it, refactored. It turned out nice (at least what I needed it to be).

What do you think? Roasts, suggestions are welcome.

0 Comments
2024/03/26
02:54 UTC

1

Can get the response with jquery

I can see the response from the server in 8econds but the page does not get it.

What am I doing wrong here ?

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Skills</title>
    <style>
  p {
    color: red;
    margin: 5px;
    cursor: pointer;
  }
  p:hover {
    background: yellow;
  }
  </style>
  <script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
  
<body>

<h1>Skills Mapping</h1>


  <div id="jd">Job Description:</div><br>
  <textarea name="jobdesc" id='jobdesc' cols="40" rows="5">WAF,DB,SQL,NOSQL,ORACLE</textarea><br>
  <div id="skillslabel">Mapped Skills:</div><br>

<br>

<button id="skills">Get Skills</button>

<div id="divskills">Skills Listing</div>
<script>
$("#skills").click(async function() {

  var txt = $("textarea#jobdesc").val();
  let jobdesc = txt.split(",");
  let myjson = JSON.stringify(jobdesc);
  // alert(myjson);
  $('#divskills').css('background-color', 'blue');

  try {
    let data = await getData(myjson);
} catch(e) {
    console.log(e);
    $('#divskills').css('background-color', 'red');
    $('#divskills').append(e);

}

  handleData(data);
});

var handleData = function (data) {
  $('#divskills').append(data);
  $('#divskills').css('background-color', 'green');

};


async function getData(myjson) {
  try {
    const response = $.ajax({
      url: "https://prod-09.uksouth.logic.azure.com:443/workflows/b11251e5eef94d09b6f2d1f217c6e372/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=ipkK2gWahsw9u4l2TQ_sc3GByUbYp6LZn9t9GCc66tM",
      data: myjson,
      type: 'post',
      dataType: 'json',
      contentType: 'application/json'
    });
    return new Promise(resolve => setTimeout(() => resolve(response), 30000));
  } catch (error) {
    console.log(error);
  }
}


</script>

</body>
</html>

0 Comments
2024/03/25
13:46 UTC

5

Dependant dynamically created select(dropdown) fields that run their .change() on page load

Hi there - I haven't been in the active programming game for some time so forgive me if the description of my problem is poorly worded.

I have select forms that are generated (using flask) from a database. The database table pre-populates the forms where a value exists, otherwise the code i'm trying to figure out will be used to fill in those blanks by selecting some dependant dropdowns (their values also come from a DB table).

I have ~11 rows of dynamically created <select>'s in two columns. one column is dependant on the other. i did manage to get that working using this:

the left column of selects are named: "sel_dstColumn_XXX" where XXX is the row ID in the database.
the right column of selects are named: "sel_dstTable_XXX" and both XXX's are the same per row. sel_dstColumn_XXX is dependant on sel_dstTable_XXX and works using this .change() below.

$("select[id^=sel_dstTable]").change(function () {
table = this.value;
my_s = this.id.split('_')[2]; #this gets the ROW_ID from the DB
$.get("/get_columns/" + table, function (data, status) {
var selID = "select[id=sel_dstColumn_" + my_s + "]";
$(selID).html("");
data.forEach(function (table) {
$(selID).append("<option>" + table + "</option>");
});
});
  });

i think the code above has the same issues as my code that's not working but its ok because i'm only working with a single field unlike further down.

the python portion is simple and looks like this for the $.get() url:

@app.route('/get_columns/<value>')
def get_columns(value):
if value in all_tables:
return jsonify(all_tables[value])
return ''

I would like to run this for all the selects with the name sel_dstTable_XXX on page load to pre-populate the dependant selects based on what (if any) values are pulled from the database. I'm trying this below (duplicate code but i dont know how to call the .change() for all the proper forms.. it doesn't work due to the variable "my_s" not properly passing into the $.get() function. i'm not understand why my_s produces the results below in the console screenshot.

$(function () {
$("select[name^=sel_dstTable_]").each(function () {
table = this.value;
my_s = this.id.split('_')[2];
console.log("expected variable my_s: " + my_s);
$.get("/get_columns/" + table, function (data, status) {
console.log("actual variable my_s:" + my_s);

# PROBLEM ON THE LINE ABOVE, i only get the last row ID (22), instead of 12, 13, 14, 15... etc produced when looping through the .each().
// var selID = "select[name=sel_dstColumn_" + my_s + "]";
// $(selID).html("");
// data.forEach(function (table) {
//   $(selID).append("<option>" + table + "</option>");
// });

});
});
  });

Console output

Thank you so much for any help - i've been fighting this all week. I hope this description makes sense.

1 Comment
2024/03/17
00:57 UTC

2

Select value stays null even when I change it using .val()

I have 2 select elements on my app: one for selecting a movie franchise and one for selecting a specific movie in that franchise.

I am trying to change the value for the franchise select after a button is clicked so that it selects the current franchise after it retrieves all of the franchises from the database and re-populates the select with the different franchise values.

Usually I will trigger the franchise select to choose the default value (first item in the options list). But I want to go back to the previous franchise I was just on.

I pass in the franchise name as the value in the .val() function but the console logs show that the new value is null.

I am able to change the value for the movie select programatically, but not the franchise select. Both elements are simple <select> elements with no special classes.

Why does it not update the value of one select but it does for the other?

2 Comments
2024/03/14
03:31 UTC

2

How can I pass an array and another var in jquery?

This works:

function add(){
$('#add_sleep_form').on("submit", function(event){
event.preventDefault();

if($('#sleep').val() == "") {
alert("Sleep Time is required");
} else {
$.ajax({
type:"POST",
data:$('#add_sleep_form').serialize(),
url:"insert_sleep.php",
success:function(data){
start();
$('#add_sleep').modal('hide');
reset(add_sleep_form);
alert("Record Added Successfully");
}
});
}
});
}

But add another var doesn't, I was wondering maybe I can send an array and a separate var

function add(){
$('#add_sleep_form').on("submit", function(event){
event.preventDefault();
var page = '<?php echo $page; ?>'; <========
if($('#sleep').val() == "") {
alert("Sleep Time is required");
} else {
$.ajax({
type:"POST",
data:{$('#add_sleep_form').serialize(), page:page}, <======
url:"insert_sleep.php",
success:function(data){
start();
$('#add_sleep').modal('hide');
reset(add_sleep_form);
alert("Record Added Successfully");
}
});
}
});
}

0 Comments
2024/03/06
13:49 UTC

2

Tablesorter

Hey everyone, I'm trying to use tablesorter to sort a table with 5 columns,the first 3 sort with no problems. The last 2 have null values and the strings are numbers and letters. The sorting isnt working with those 2. How can I fix this?

0 Comments
2024/03/05
14:08 UTC

2

Figure out what file is calling my jquery script?

Hello, is it possible to figure out what file is calling my jquery script? I have a couple different forms that are relatively the same and I want to use the same jquery file for them as this would same me a lot of work and from having to deal with multiple files.

I'm looking for something like this

if file1 is calling this jquery script{
    do this thing...
}
else if file2 is calling this jquery script{
    do that thing...
}
else if file3 is calling this jquery script{
    do that other thing...
}

I had the idea of looking for specific elements I know would only be present on each page, but you never know I may add them on later on for some reason, plus the other way is much more reliable.

Thanks for any help!!!

3 Comments
2024/02/23
01:16 UTC

2

Why .clone() is needed in this example?

The last time I used jQuery in depth was probably 12 years ago.

New gig and...we're using a ton of jQuery here. Which is odd. But hey, brushing off some old skills. But I'm rusty.

I'm stuck on this concept here:

//create a jQuery element
$objectToAppend = "<div class'hello'></div>";

//now append this to some previously defined other jquery objects:
$object1.append($objectToAppend);
$object2.append($objectToAppend);
$object3.append($objectToAppend);

In that example, only object3 will render with the $objectToAppend.

The fix is to clone the object each time I append:

//append a copy to each object :
$object1.append($objectToAppend.clone());
$object2.append($objectToAppend.clone());
$object3.append($objectToAppend.clone());

Why do I need to clone the object each time?

Intuitively if feels like .append() should make a copy of whatever object you are appending to it by default. But obviously it doesn't...it only allows a single instance of that object to be appended (removing from any previously appended elements). Just curious as to why that is?...is there an example of why you'd actually want that latter behavior?

2 Comments
2024/02/15
04:52 UTC

0

jquery if statement not working

trying to get a class removed from a div only on instances where screen size is above a certain width. but this doesn't appear to be working, can someone please help me debug?

<div class='cool-wrapper four-box hiddenPromoWrapper' id='funnyWrapper'>

if (jQuery('#funnyWrapper').hasClass('slick-initialized') && ($(window).width() > 767)) {

jQuery('#funnyWrapper').slick('unslick');

jQuery('#funnyWrapper').removeClass("hiddenPromoWrapper");

}

2 Comments
2024/02/07
21:04 UTC

2

Function animate scale

hey guys, i just cant wrap my head around. I want to animate the scale of a cube, but with every code i use it starts from zero, but it should start from their standard position. Can somebody help me there :) thanks mates <3

0 Comments
2024/02/03
16:57 UTC

1

get status of database load

I have a front end where a user can upload an excel document. The excel documents can have several thousand lines to process.

once PHP gets the file, it will do some database operations. I would like to show a progress update to the user. Example: Processing: 13/104 and have it updated as it moves between records.

I'm really not sure where to start here.

0 Comments
2024/02/02
01:21 UTC

0

jQuery has Normalized User Experience and Appearance Across All Platforms & Browsers but Vanilla JS Leaves it up to the Browser's Implementation

I love Vanilla JavaScript and only use jQuery for the Widgets. To me it is very important that users have exactly the same appearance and most importantly the same functionality in all browsers and all platforms when it concerns objects on a web page. I am mainly referring to the jQuery Widgets. Over the years that I used jQuery there was no HTML object equivalent to many until HTML5.

As an example consider the HTML input type="date" as compared to the jQuery ui Datepicker. The vanilla JS version looks similar in different browsers but not exactly the same, some have a Clear and Today button and some do not. How do you explain that to your users?

Another example is vanilla JS input type="datetime-local" which jQuery has no current equivalent as far I know. In Chrome, Edge, and Opera they are basically the same with the scrollable hh, mm and am/pm, but in Firefox and Safari you have to manually type the time into the input box. Any user who first used Chrome and then opened the same page in Firefox would ask "Where is the time scroll list?".

That having been said, lets talk about vanilla JS HTML 5 specifications given to browser companies so they could create objects. Apparently certain feature might be optional for a given object (i.e. Clear or Today Buttons) . This might become a nightmare for developers in the future unless a more stringent standard is enforced.

Why not have a third party create objects that all browsers MUST use to make thing uniform? Basically that is what jQuery is good for.

Let me go way out there now and ask the big question, Does Congress have to pass a law to force companies that make browsers use a common set of objects?

Your thoughts?

4 Comments
2024/01/29
02:42 UTC

2

Change the background color with ripple effect

Hello.

I am looking for a library with ripple effect (material design) to change the background color of the element with it. For example: i click on a button on a div with white background, and then with ripple effect the background color of the div is changing. Surprisingly, i did not found anything like this. If you know that kind of lib, please, let me know.

0 Comments
2024/01/19
23:38 UTC

2

Making an image inside of an element stretchable on mobile

I have an element that's set to 90% of the user's viewport width. Inside of the element is an image that is set to fill the element, but the dimensions of the image on the server are set to 1000px width **.

So if the user is on a mobile device with, say, 360px in width, then the browser will resize the image to 324px width.

Any suggestions on making it so that the mobile user can stretch the image, without stretching the element or page?

**Note, the 90% width element is loaded when the user clicks to view a larger version of the thumbnail image. And I'm intentionally saving it at 1000px so that the user can zoom in on it without pixelation. This is still in beta, though, so I can change that to a larger size if necessary.

0 Comments
2024/01/15
06:41 UTC

1

Script not working

Hi, can somebody tell me why the script on my (Wordpress) website is not working?
Nothing happens with the class element when the links are clicked.

        jQuery(document).ready(function($) {
            $('.cat-list_item').on('click', function() {
                $('.cat-list_item').removeClass('active');
                $(this).addClass('active');
                $.ajax({
                    type: 'POST',
                    url: '/wp-admin/admin-ajax.php',
                    dataType: 'html',
                    data: {
                        action: 'filter_projects',
                        category: $(this).data('id'),
                    },
                    success: function(res) {
                        $('.project-tiles').html(res);
                    }
                });
            });
        });   

5 Comments
2024/01/09
10:54 UTC

2

Breaking Down IT Salaries: Job Market Report for Germany and Switzerland!

Over the past 2 months, we've delved deep into the preferences of jobseekers and salaries in Germany (DE) and Switzerland (CH).

The results of over 6'300 salary data points and 12'500 survey answers are collected in the Transparent IT Job Market Reports.

If you are interested in the findings, you can find direct links below (no paywalls, no gatekeeping, just raw PDFs):

https://static.swissdevjobs.ch/market-reports/IT-Market-Report-2023-SwissDevJobs.pdf

https://static.germantechjobs.de/market-reports/IT-Market-Report-2023-GermanTechJobs.pdf

0 Comments
2024/01/05
07:39 UTC

3

Is $(window).on( "load", () => { } essentially the same as if (document.readyState === 'complete')

I'm transitioning a site from JavaScript to jQuery 3.3.1. It's been awhile since I've messed with jQuery, though!

Can you all confirm, is

$(window).on("load", () => {
  console.log('loaded');
});

essentially the same as:

var interval = setInterval(() => {
    if (document.readyState === 'complete') {
        clearInterval(interval);

        console.log('loaded');
    }
}, 500);

In production, I need to wait for Adsense banners to load so that I can check the status, but I'm not sure if $(window).on('load'...) runs before or after the banners complete.

7 Comments
2023/12/30
19:19 UTC

3

Can anyone please find the issue in this code

Hi,Below is my existing code. In center there is an image and four boxes at each corner of circle. When i mouseover on image or four boxes, image will be replaced with respective text depending on which box we mouseover.My issue is when i mouseover on image it is working as expected, but on mouseout, it is not restoring image. But for 4 boxes it is restoring image properly.

https://codepen.io/thambyz/pen/eYXYmVW

5 Comments
2023/12/21
13:13 UTC

1

Unable to Detect Change on Dynamically Generated Checkboxes

Great, you've provided a clear summary of the issue. Now, you can incorporate this into your Stack Overflow post. Here's an updated version of the description section in the template:

---

**Issue: Unable to Detect Change on Dynamically Generated Checkboxes**

**Description:**

I'm facing an issue where dynamically generated checkboxes are not triggering the change event when clicked. To address this, I used `$(document).on("change", ".integration-event-checkbox", ...)` for event delegation. While this successfully attaches the event, I'm encountering a problem when attempting to retrieve checked checkboxes and update the URL dynamically.

Below is a simplified version of the code:

**JavaScript File (`script.js`):**

```javascript

$(document).ready(function() {

const $checkboxes = $("#checkboxes");

const integration = [ {all:["push","pull"]},{all:["post","get"]},{all:["put","delete"]}]

const $eventCheckboxes = $(".integration-event-checkbox");

// This event handler is not being triggered for dynamically generated checkboxes

// $(document).on("change", ".integration-event-checkbox", (e) => {

// console.warn("Checkbox changed");

// console.warn("event",e);

// update_url();

// e.preventDefault();

// e.stopPropagation();

// });

const events = display_box(integration[0].all)

$checkboxes.html(events);

function display_box(integration){

const checkboxesHTML = integration.map(item => `

<label><input type="checkbox" class="integration-event-checkbox" value="${item}" />

${item}

</label>

`).join('');

return checkboxesHTML;

}

function update_url() {

const selectedEvents = $eventCheckboxes.filter(":checked").map(function () {

return this.value;

}).get().join(",");

console.log("SELECTED EVENTS: ", selectedEvents);

// Add the checked events to the URL

const eventsParam = selectedEvents.length > 0 ? `&events=${selectedEvents}` : '';

console.log("Events Param: ", eventsParam);

console.log("event checkboxes: ", $eventCheckboxes);

}

});

```

**Issue Details:**

  1. The `$(document).on("change", ".integration-event-checkbox", ...)` event handler is not capturing changes for dynamically generated checkboxes.

  2. When attempting to retrieve checked checkboxes using `$eventCheckboxes.filter(":checked").map(...)`, both `selectedEvents` and the `$eventCheckboxes` collection are empty.

**Steps to Reproduce:**

  1. Dynamically generate checkboxes using JavaScript.

  2. Attach a change event using `$(document).on("change", ".integration-event-checkbox", ...)`.

  3. Click on dynamically generated checkboxes and observe the lack of change event triggering.

  4. Attempt to retrieve checked checkboxes using `$eventCheckboxes.filter(":checked").map(...)` and notice that the result is empty.

**Expected Behavior:**

The change event should be triggered for dynamically generated checkboxes, and the code should correctly retrieve and display the checked checkboxes.

https://preview.redd.it/c533177jbn6c1.png?width=1849&format=png&auto=webp&s=61bf198eac02c7c9c34ebc6cbb8aa1fabe18c5c3

0 Comments
2023/12/16
11:54 UTC

1

JSDataTable JQuery - Pass ID to next API Call

I have a JSDataTable that returns a list of Products from the database, from tblProduct.

[HttpGet]
public IActionResult GetAll(int ID)
{
    List<Product> productList = _unitOfWork.Product.GetAll().ToList();
    return Json(new { data = productList });
}

https://preview.redd.it/vf0e1mly2z5c1.png?width=656&format=png&auto=webp&s=49a51abaed7963f5be3353c5fb0e62534cab9a71

Clicking on View, will then display the Product Details page for that product, with the ID being passed in the URL: /Product/View?id=2 (or whichever ID is of that product)

function loadDataTable() {
    dataTable = $('#tblData').DataTable({
        ajax: { url: '/Product/GetAll' },
        columns: [
            { data: 'productName', "width": "10%" },
            { data: 'productBrand', "width": "25%" },
            { data: 'productDescription', "width": "55%" },
            {
                data: 'id',
                "render": function (data) {
                    return `<div class="w-75 btn-group" role="group">
                    <a href="/Product/View?id=${data}" class="btn btn-primary mx-2"><i class="bi bi-pencil-square"></i> View</a>
                    </div>`
                },
                "width": "10%"
            }
        ]
    });
}

I need to be able to pass that ID into another API Call

CS:
[HttpGet]
public IActionResult GetProduct(int ID)
{
    IEnumerable<StorageProduct> objStorageProduct;
    objStorageProduct = _unitOfWork.StorageProduct.GetAll(includedProps:"StorageLocation,Product").ToList();
    objStorageProduct = objStorageProduct.Where(u => u.ProductID == ID);
    return Json(new { data = objStorageProduct });
}

JS:
function loadDataTable(ID) {
    dataTable = $('#tblStorageProduct').DataTable({
        "ajax": { url: '/Product/GetProduct?ID=' + ID },
        "columns": [
            { data: 'storageLocation.storageLocationName', "width": "10%" },
            { data: 'product.productName', "width": "10%" },
            { data: 'quantity', "width": "25%" }
        ]
    });
}

So then it will display the grid with the columns above, displaying the location, product and quantity for that location. I've tried multiple ways, but my grid always says no data available. The Json does return all the fields, I'm just unsure how to parse that ID in so it works on the new page.

Is it possible? Any help would be appreciated as I am fairly new to JQuery/ajax calls.

0 Comments
2023/12/13
02:29 UTC

4

Trusted Types violation in jQuery

I used jQuery 1.9.1 in a Google Apps Script project that recently quit working in chrome browsers.

If I use developer tools and find the issue, it is upset at this line because "Trusted Type expected, but String received"

d.innerHTML = "  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",

It's a simple project that does some quick translating.
I tried multiple versions of jQuery and none I have tried work and some have more than 1 issues.
For example, I used 3.7.1 and it is now upset at two lines for the same reason.

 r.appendChild(e).innerHTML = "<a id='" + S + "' href='' disabled='disabled'></a><select id='" + S + "-\r\\' disabled='disabled'><option selected=''></option></select>",

and

xe.innerHTML = "<textarea>x</textarea>",

It seems to be the issue is within the query library, but I'm not a programmer so I'm sure they're good and I'm missing something but I have no idea what.

Any ideas or help?
Thanks!

2 Comments
2023/11/28
18:55 UTC

Back To Top