jQuery

16K

Solutions

27

Articles & Videos

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'm using jquery ui autocomplete
I want to have a drop down list on my page also. So my DropDown list will display countries.
If I select USA from the drop down list then the autocomplete should only show suggestions for states in USA.

Anyone know a good link to a good example where a drop down list filters the autocomplete suggestions?
0
Guide to Performance: Optimization & Monitoring
Guide to Performance: Optimization & Monitoring

Nowadays, monitoring is a mixture of tools, systems, and codes—making it a very complex process. And with this complexity, comes variables for failure. Get DZone’s new Guide to Performance to learn how to proactively find these variables and solve them before a disruption occurs.

I had this question after viewing how to get id from url using php and Jquery.

This is the php:

$url = filter_var($_GET['id'], FILTER_SANITIZE_URL);
$stmt = $link->prepare("SELECT `n_title`, `n_dateTime`, `n_article` FROM `news` WHERE `id` = ?");
$stmt->bind_param("i", $url);

if (!$stmt->execute()) echo "Execute Error: ($stmt->errno)  $stmt->error";
$result = $stmt->get_result();

if ($result) {
	$row = $result->fetch_assoc();
	$n_title = sanitize($row['n_title']);
	$n_dateTime = sanitize(row['n_dateTime']);
   $n_article = sanitize($row['n_article]);
	
	$news_detail[] = array(
	
		"n_title" =>$n_title,
		"n_dateTime" => $n_dateTime,
           "n_article" =>$n_article
	
	);
	
} else {
	
	echo "No record found";
}

$stmt->close();
echo json_encode($news_detail);

Open in new window


This is the jQuery/Ajax:

myApp.onPageInit('article', function (page) {
   var id = page.query.id;
   $$.ajax({
	   url: "news-detail.php",
	   type:"GET",
           data: {id: id}, 
	   success: function(data) {
		console.log(data);
		 
	   },
   });
});

Open in new window


Perhaps I want to show the title at the top of the page and the date at the bottom of the page. Do I need to put everything into divs?

So, at the top of the page I would have <div id="news-headline"></div> and at the bottom of the page I might have <div id="article-date"></div>.

Is that the correct way to do it? And if so, how would I get the values into those divs? When using a while loop for lost of records I used:

$$.each(data, function(item) {

Open in new window


but since I am not looping through records, and only getting one row, I am not entirely sure how to get that data.
0
Hi experts, I'm trying to implement JQuery here ($("Qty").change();) where I can be able to compute the result between the two fields upon adding  row on a table. My goal here is to have the result bet the two input, the id="Qty" and the id="rd". I want to have an auto answer to be filled in the result, id="utotal". The codes below won't work.., any help please! Thank you.

<!DOCTYPE html>
<html>
<style>
table,th,td {
  border : 1px solid black;
  border-collapse: collapse;
}
th,td {
  padding: 5px;
}
tfoot {color:red;}
</style>
<table id="Tab1">
<tr>
  <th>Quantity</th>
  <th>Price</th>
  <th>Total</th>
</tr>
</table>
<br/>
<button onclick="return AddNow()">Add row</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script>
function AddNow() {
   var q = parseInt("2.00");
   var p = parseInt("2.50");
  
  var table = document.getElementById("Tab1");
  var row = table.insertRow(table.rows.length);
  
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);
  
  cell1.innerHTML = '<input type="text"  id="Qty" value="' + q + '"' + 'onchange="myRowTotalPOS(this.parentElement.parentElement)"/>';
  cell2.innerHTML = '<input type="text" id="rp"  value="' + p + '"' + ' readonly/>'; 
  cell3.innerHTML = '<input type="text" id="utotal" />';
}

function myRowTotalPOS( row )
    {
		Qty = row.cells[0].firstChild.value;
		if( Qty != '' && Qty != null ) Qty = Qty.replace( ',', '' ); 
      

Open in new window

0
I am using ajax and jQuery to to query the database and display records from the database. I am then appending the results. The trouble I am having is that when the user taps (this is a mobile app) the article they want to view, it should take them to the details of that particular article. In order to do that I need to send the ID of that article to the detail page.

This is the jQuery  (I am using Framework7 which uses $$ instead of $). This lists the articles.

function newsFeed() {
	$$.ajax({
		url: "newsfeed.php",
		type: "POST",
		dataType: "json",
		success: function (data) {
			$$.each(data, function (item) {
				$$("#newsFeed").append(`

					<li>
						<a href="article.html?$id={data[item].id}" class="item-link item-content">
							<div class="item-media"><img src="img/${data[item].n_pic}" width="80"></div>
								<div class="item-inner">
								<div class="item-title-row">
									<div class="item-title news-headline">${data[item].n_title}</div>
								</div>
							<div class="item-text"></div>
									<div class="date-time">${data[item].n_dateTime}</div>
							</div>
						</a>
					</li>	
				`);
			});
		},
	});
}

Open in new window


I want to GET that id that is being sent in PHP:

$url = filter_var($_GET['id'], FILTER_SANITIZE_URL);
$stmt = $link->prepare("SELECT `n_title` FROM `news` WHERE `id` = ?");
$stmt->bind_param("i", $url);

if (!$stmt->execute()) echo "Execute Error: ($stmt->errno)  $stmt->error";
$result = $stmt->get_result();

if ($result) {
        $row = $result->fetch_assoc();
	$n_title = sanitize($row['n_title']);
	echo $n_title;
	
} else {
	
	echo "No record found";
}

$stmt->close();

Open in new window


This is the jQuery that is trying to get the results:

myApp.onPageInit('article', function (page) {
   $$.ajax({
	   url: "news-detail.php",
	   type:"POST",
	   success: function(data) {
		   console.log(data);
	   }
	   
   })
});

Open in new window


The error I get is:

Undefined index: id

So, I guess that php is not able to get the id being passed in the jQuery.
0
I have the following piece of code that is needed to build and add rows under the right headings in an html table.
var mileStoneHtml="";
		var typeArray = [];
		var headingName = "";
		for(var i =0; i < data.d.results.length; i++) 
		{	
			headingName = data.d.results[i].Milestone_x0020_Type;
			
			if (typeArray.indexOf(headingName) === -1){
				typeArray.push(headingName);
				
				
				tableRow = document.createElement("tr");
				tableRow.id=headingName;
				tableRow.style.backgroundColor = "#EEEEEE";
				tableCol = document.createElement("td");
				tableCol.colSpan = 5;
				tableCol.textContent = headingName;
				tableRow.appendChild(tableCol);				
				console.log(tableRow);
				tbl = document.getElementById("tblMilestone");
				console.log(tbl);
				console.dir(tbl);
				tbl.appendChild(tableRow);
			}
					mileStoneHtml = "<tr>"+
					"<td>"+data.d.results[i].MilestoneDescription+"</td>"+
					"<td>"+data.d.results[i].Planned_x0020_Date+"</td>"+
					"<td>"+data.d.results[i].Revised_x0020_Date+"</td>"+
					"<td>"+data.d.results[i].Actual_x0020_Date+"</td>"+
					"<td>"+data.d.results[i].Milestone_x0020_Type+"</td>"+
				"</tr>";		
				
				var newRow = $("#"+headingName).append(mileStoneHtml);
				console.log(newRow);
//				document.querySelector("#tblMilestone").appendChild(mileStoneHtml);					
		}													

Open in new window


It needs to look like this
correct rendering
but it looks like this
incorrect rendering
0
Hi Experts

Could you point how to obtain the values from the Javascript  Objects?

Javascript
console.log(Object.values(where));

Open in new window


Produced
img001
So, what's needed to obtain these Object's values?

Thanks in advance!
0
Hi

See my code: https://codepen.io/petewinter/pen/weqWeq

Can you please help with the following...

1) My list should be sorting alphabetically. I assume this is not happening correctly due to the tags within the <li>, but I'm not sure how to edit the code?
2) When a checkbox is checked I would like selected checkboxes to go to the top of the list alphabetically, then when unchecked go back back down and sort alphabetically again.

Help would be much appreciated.
0
I'm looking for a way to asynchronously load the contents of a whole div. I'd like to delay the loading of everything in the div. Right now, everything is loaded all at once and it's not bandwidth efficient.

https://codepen.io/anon/pen/GENGJW
0
I have an input field of type checkbox. I would like to retain the check status after page reload/refresh. Below is my codes:
HTML
<input type="checkbox" title="Check/Uncheck to show or hide   your mobile number." id="mobile<?php echo $mobile; ?>"  class="mobile" name="<?php echo $mobile; ?>" value="<?php  echo $mobile; ?>" style="visibility:hidden">

Open in new window


JQUERY This one works. When I checked the checkbox, the .mobile class respond accordingly - it hide and show.

$(document).ready(function() {
    $('.mobile').change(function() {
        if (this.checked)
            $('.MobileIcon').hide('slow');
        else
            $('.MobileIcon').show('slow');

    });
});

Open in new window


The below line of code did not work

$(function() {
    $("input:checkbox").each(function() {
        if (localStorage.getItem(this.value) == 'checked') {
            $(this).attr("checked", "true")
        }
    })
$("input:checkbox").click(function() {
        if ($(this).is(':checked')) {
            localStorage.setItem(this.value, 'checked');
        } else {
            localStorage.removeItem(this.value);
        }
    });
});

Open in new window


This is not working. The checked disappear when I reload the page. I want the checkbox to remain checked even at page reload, so that my hide and show would also persist.
Please any help to get this working would be appreciated.
0
So, I am really trying to get my head around JSON and I have tried this which works but I wanted to know if there is a better way to do it or if this okay. I am actually playing around with developing a hybrid mobile app which uses a php and mysql backend. I have to use ajax to retrieve data and I want to also use JSON.

This is the jQuery/Ajax. The double dollar signs are not a typo, that is the correct syntax for the application but it is identical to jQuery as far as I know.

$$( "#submit" ).click(function(e){
		$$.ajax({
			url:"content.php",
			type:"POST",
			dataType:"json",
			success: function(data) {
				var len = data.length;
				for(var i = 0; i<len; i++) {;
					var user_name = data[i].user_name;
					$$( "#phpcontent" ).append(`
					<li class="item-content">
						<div class="item-inner">
						<div class="item-title">${user_name}</div>
						</div>
					</li>
					`);
				}
			}
		});
	});

Open in new window


This is the php for content.php

$stmt = $link->prepare("SELECT `user_name` FROM `users` ORDER BY `user_name` DESC");
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
	while($row = $result->fetch_assoc()) {
		$user_name = sanitize($row['user_name']);
		
		$return_array[] = array(
		
			"user_name" => $user_name
		
		);
	}
}
$stmt->close();
echo json_encode($return_array);

Open in new window


What I have noticed in all the examples I have looked at is that the database results have to be put into an array in order to use json_encode. Am I correct in saying that or is it just a coincidence that every example I looked at did that?
0
[Webinar] Learn How Hackers Steal Your Credentials
LVL 8
[Webinar] Learn How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Ref: Responsive & Fluid Sidebar Plugin with jQuery and Hammer.js
The trigger to activate the off canvas menu is located in the div class"sidebar-trigger" which essentially wraps around the off canvas sidebar.
I would like to add a second trigger that I can place outside of this wrapper that will also toggle the off canvas menu however documentation on how to accomplish this is sparse.
Ideas welcome.
N
0
1. I followed examples in the link below and coded a map. It works. You can see a map here:

 http://leafletjs.com/examples/choropleth/

You see if you zoom out, you'll see Hawaii and Alaska.

2. I've been asked to make it look like this...Have Alaska and Hawaii next to the US
https://www.highcharts.com/maps/demo/us-counties

3. The Leaflet link in step 1 has the "us counties.js" file

4. I looked at Highchart's JS file (you can see the link in JSFiddle that comes with Highcharts, step 2 above).
    Looks like they have Alaska and Hawaii bundled in a separate section of the JS file and then they have the rest of the states.

Anyone has worked with Leaflet.Js and got Hawaii and Alaska moved next to the US?
0
I've got an AJAX form dynamic happening. Everything is working just like the client wants with the exception of what happens when a user goes to login and nothing is found in the database.

When the user clicks the "submit" button, here's the code that is called:

$('#findPortalUser').click( function(event){
			
			event.preventDefault();
			
			if (validateForm()) {
				$("#verify_form").hide();
				
				var out = {
					'usrDOB' : $('#usrDOB').val(),
					'usrEEID' : $('#usrEEID').val(),
					'cpID' : 574,
					'displayLinks' : $('#displayLinks').val()
					};
					
				$.post('api_bmcjax.php?p=verify&displayLinks=false&linkType=surveyevents', out, function(data)
				{
					$('#window').html(data);
				});
			}
		});

Open in new window


Notice the "$('#verify_form').hide()" command.

If nothing is returned, I need that div to be visible.

How?
0
I am using Modernizr to detect if autoplay is available in the browser. Then, I am displaying either a video or a Javascript-based slide show depending on the result. Here is my code:

videoAutoPlayCheck=setInterval(videoCheckAutoPlay, 1000);
videoCheckAutoPlay();

function videoCheckAutoPlay(){
	Modernizr.on('videoautoplay', function(result){
		if (Modernizr.videoautoplay){
			//PLAY VIDEO
			window.clearInterval(videoAutoPlayCheck);
		} else {
			//PLAY SLIDE SHOW
			window.clearInterval(videoAutoPlayCheck);
		}
	});
}

Open in new window


I am getting unpredictable results in Chrome, however this seems to be working in all other browsers. Researching the issue on Google, there are posts from a couple years ago describing what I am seeing. However, I would have thought that enough time has passed that Modernizr would have fixed that issue.

To describe what is happening, sometimes Chrome loads the video, sometimes the slide show. There doesn't seem to be any way to predict... in fact, sometimes reloading the page brings the opposite result as the previous page load.

Is there anything wrong with my code, or is this still a known issue with Modernizr? Or should I be looking for some other solution?

Thank you.
0
I want to ignore a function if a specific button/submit is clicked.  If I have a submit button with an ID of submit, how do I not run a function?  

If Clicked Do NOt Run.
0
I have created a new angular project via angular-cli.

I now what to install jQuery but installing it via npm.

How can I do this?
0
I'm working on a page that I didn't write and I want to understand what I'm doing and what's happening.

Here's a portion of the code that has me puzzled. I want to explain to you what I comprehend and then ask whoever's willing to fill in the gaps.

$.post('api_woodward.php?p=verify&displayLinks=false&linkType=surveyevents', out, function(data)

This is a JQuery AJAX form function. The first part is the URL the form content is being posted to (woodward.php). The second part, "out" - I've no clue. The last part, function(data) - I'm looking at https://api.jquery.com/jquery.post/ and it seems like this is code to display what happens in the event of a successful form transmission.

As far as "out" is concerned, I think I know what it is, but I want some other eyes on it.

When the content is posted to the api_woodward.php page, "p=verify" steers the content to a specific function on the page. Within that function, there's another piece of syntax that kicks into gear based on the linkType being "surveyevents." If that's the case, you have this:

        if ($linkType == 'surveyevents') {
            $result['usrID'] = encryptVals($result['usrID']);
            $out .= <<<OUT
				<script>
				$('#verifyUseryes').click(function($event){		
					//event.preventDefault();
					$.post('api_woodard.php?p=d11', {'ui':'{$result['usrID']}', 'ei':'{$result['empID']}'}, function(data){
						$('#window').html(data);
					});
				});
				

Open in new window

0
Hi,

I am in need of some assistance with a character search in any string for the followign characers

-
[
]
*
!

Any and all help would be very much appreciated.

Thanks

Simon
0
I'm quite new to jquery.
I have a simple jquery function which takes the value from two html select inputs ( #number1 and #number 2), multiples the values together and assigned a string value to the DIV element (#total) according to what the calculated value(total) is.

Everything works fine except the if statements. I'm not too sure how best to do this in jquery?


 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#number1, #number2").change(function(){
    var cons = $("#number1").val() || 0;
    var likely = $("#number2").val() || 0;
    
    var total = (cons * likely)
      
    if ((total == "0"))
     { var result = "N/A";}
    else if ((total >= "1") && (total <= "2"))
     { var result = "Low";}
    else if ((total >= "3") && (total <= "4"))
     { var result = "Medium";}
    else if ((total >= "6") && (total <= "9"))
     { var result = "High";}
    else if ((total >= "12") && (total <= "16"))
     { var result = "Immediate";}    
       
    
    $("#total").html(result);    
    });
});



</script>';

echo '<form><table class="my-table">
    <thead>
        <tr>
            <td>Type</td>
            <td>Consequence</td>
            <td>Likelyhood</td>
            <td>Total</td>
        </tr>
    </thead>
    <tbody>
        <tr data-row-num="1">
        <td>Risk Self</td>
        <td><select id="number1">
              <option value="1">1</option>
              

Open in new window

0
Free Tool: IP Lookup
LVL 8
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Hello experts,

I've been struggling with this for some days now. I use the function below to control a youtube video embedded with an iframe. The initialize function works properly. The problem is the onPlayerStateChange function. I'm trying to control the pause and play using the same button but it doesn't seem to run properly. It doesn't pause the video and the video itself cracks or lags.

var player, time_update_interval = 0;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('videod', {
        playerVars: {
            color: 'white'
        },
        events: {
            'onReady': doThisFirst,
            'onStateChange': onPlayerStateChange
        }
    });
}

function doThisFirst(){
    updateTimerDisplay();
    clearInterval(time_update_interval);
    time_update_interval = setInterval(function () {
        updateTimerDisplay();
    }, 1000);
    $('#volume-input').val(Math.round(player.getVolume()));
}

function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING) {  // If video is playing…
              var stop = document.getElementsByClassName('playButton');
              stop[0].click(player.pauseVideo());
        }
        else{    // If video – pause
            var start = document.getElementsByClassName('playButton');
            start[0].click(player.playVideo());
        }
      }
0
I am using handlebars and ran into an issue with trying to group by a category but I was able to fix that by using underscorejs.  Now my issue is using my object categorized into arrays into my template.  Here's an image of what I see in the developer tools:
Object with two arrays
As you can see, it's an object with two arrays.  I got the data to show by doing the following but as you will see, it's not very efficient because there are actually have 6 categories and not just two.
<!-- Handlebar Js Template Starts Here -->
   
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.10/handlebars.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script type="text/javascript" src="../nrm/SiteAssets/projectMilestone.js"></script>

<script id="projectMilestone-template" type="text/x-handlebars-template">
 
<table border=1> 
 	<tr>
 		<th colspan="7">Milestones</th>
 	</tr>


	<tr>
		<td>Milestone Description</td>
		<td>Planned Date</td>
		<td>Revised Date</td>
		<td>Actual Date</td>
		<td>Type</td>
	</tr>
{{#Construction}}	
	<tr>
		<td>{{ MilestoneDescription}}</td>
		<td>{{ Planned_x0020_Date}}</td>
		<td>{{ 

Open in new window

0
Hi experts, The code below is able to export table to excel. However, I want to use a button .click function before the download starts. Any help please!
 
<!DOCTYPE html>
<html>
	<head>
		<title>jQuery Boilerplate</title>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
		<script src="../dist/jquery.table2excel.min.js"></script>
	</head>
	<body>
    <button class="WinExcel">Export</button>
    
		<table class="table2excel" data-tableName="Test Table 1">
			<thead>
				<tr class="noExl"><td>This shouldn't get exported</td><td>This shouldn't get exported either</td></tr>
				<tr><td>This Should get exported as a header</td><td>This should too</td></tr>
			</thead>
			<tbody>
				<tr>
					<td>data1a with a <a href="#">link one</a> and <a href="#">link two</a>.</td>
					<td>data1b with a </td></tr>
				<tr>
					<td>data2a with a <input tyle="text" value="text value">.</td>
					<td>data2b with a <input tyle="text" value="second text value">.</td>
				</tr>
			</tbody>
			<tfoot>
				<tr><td colspan="2">This footer spans 2 cells</td></tr>
			</tfoot>
		</table>

		<script>
			$(function() {
				$(".table2excel").table2excel({
					exclude: ".noExl",
					name: "Excel Document Name",
					filename: "myFileName",
					fileext: ".xlsx",
					exclude_img: true,
					exclude_links: true,
					exclude_inputs: true
				});
			});
    
		</script>
    
	</body>
</html>

Open in new window

0
http://maps.aerophotos.cf/test.
Basically make the markers update every second or so from the JSON file aswell as display the data in the JSON file i.e altitude callsign etc when clicking on marker.
0
Hi I'm using a datatable with column filter option and has the functionality to export the table content to excel. While I'm exporting the content the filter code gets exported along with the header. Please help.

Code:
Javascript:
<script>
    $(document).ready(function() {
        $('table').DataTable({
         dom: 'Blfrtip',
            buttons: [{
                text: 'View in Excel',
                extend: 'excelHtml5',
                exportOptions: {
                    modifier: {
                        selected: true
                    },
                    columns: [0, 1, 2, 3],
                    format: {
                        header: function(data, columnIdx) {
                            return data;
                        },
                        body: function(data, column, row) {

                            // debugger;
                            return column === 4 ? "" : data;
                        }
                    }
                },
                footer: false,
                customize: function(xlsx) {
                    var sheet = xlsx.xl.worksheets['1.xml'];
                    //$('c[r=A1] t', sheet).text( 'Custom text' );//$('row c[r^="C"]', sheet).attr('s', '2');
                }
            }],
            fixedHeader: true,
            pageLength: -1,
            initComplete: function() {
                this.api().columns([2]).every(function() {
     …
0
Hello
I am using jquery chosen for my dropdown and cannot get the change event to fire. I have tried multiple options but nothing seems to work.

I have also tried using the class name instead of the id. I would be grateful if someone could point out my error. Thanks

jQuery chosen homepage

<script type="text/javascript">
  $(function() {
    $("#userAdmin").chosen().change(function() {
      //window.location = $(this).val(); 
      $(this).valid();
      alert($(this).val());
    });
  });
</script>

Open in new window


html

<td>
  <select data-placeholder="Select a User" class="chzn-select" style="width:250px;" id="userAdmin" name="userAdmin">
    <option value="users.php">User Admin</option>
  </select>
</td>

Open in new window

0

jQuery

16K

Solutions

27

Articles & Videos

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