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'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
Business Impact of IT Communications
Business Impact of IT Communications

What are the business impacts of how well businesses communicate during an IT incident? Targeting, speed, and transparency all matter. Find out more in this infographic.

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
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
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
Hello
I have an external javascript file and was wondering if it is possible to include an html div in the page. For example like the code below. I have searched google but cannot find a definitave answer. Many thanks

<div>
   <input type="button" value="Export to excel" id='excelExport' />
   <input type="button" value="Export to pdf" id='pdfExport' />
   <input type="button" value="Print Data" id='print' />
</div>

Open in new window

0
I have a sidebar that converts to a tab for smaller screen sizes. This is mostly done with css, using JavaScript to open and close the tab. When the tab is open, I've made it so that the user can click anywhere on the screen to close it.

My resize() function will convert the tab back to a sidebar, but, if the user clicked on the tab at the smaller size, then enlarges their browser, clicking anywhere on the screen will make the sidebar disappear.

Basically, all I need to be able to do is to remove the onclick I've set up here, something like
    if($(window).width() > 751
    {
        {remove the event set up in $(document).click(function(e)}
    }  

Open in new window


I've tried using the jQuery ".off" function; stop propagation - nothing seems to work. Even with the right syntax, I'm not sure .off will do the trick, which. I think, may turn off any event clicks which, of course, I don't want to do. Things just need to return to normal when screen size is greater than 751.

    <script type="text/javascript">
        $(document).ready(function()
        {
            $('#SideTab').click(function()
            {
                if($('#Sidebar1').css('margin-left') != '-300px')  // The Sidebar/Tab is open
                {
                    $('#Sidebar1').css('margin-left', '-300px');  // Hide the Sidebar (only Tab is exposed)
                }
                else
                {
                    $('#Sidebar1').css('margin-left', '0px');  // Open the 

Open in new window

0
I am using REST API with SharePoint 2013 and I want to know if the following url endpoint is legal or if there is a better way?
 //http://myspsite.com/nrm/_api/web/lists/getbyTitle('My_Project_Modules')/items?$select=DIR,Station,Title,Building_x0020_Number&$filter=Project_x0020_Number eq '402-CSI-001'     //<---  Works when I paste it in the browser
 var projNum = '402-CSI-001';
var endPointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbyTitle('My_Project_Modules')/items?$select=DIR,Station,Title,Building_x0020_Number&$filter=Project_x0020_Number eq "+projNum;  //<---  Not valid when I run it in my code

Open in new window


Error I get in my js file
rest api error
js file
function loadSPItems() {
var projNum = '402-CSI-001';
var endPointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbyTitle('My_Project_Modules')/items?$select=VISN,Station,Title,Building_x0020_Number&$filter=Project_x0020_Number eq "+projNum;//,ProjectNumber,ApprovalStatus,ProjectExecutionStatus”;
var headers = { 
	"accept": "application/json;odata=verbose" 
}
 
jQuery.ajax({ 
	url: endPointUrl, 
	type: "GET", 
	headers: headers, 
success: function (data) {
	console.dir(data);
}, 
	error: function (err) { 
	alert("Error Occured:" + JSON.stringify(err)); 
}
 
});
 
}

loadSPItems();

Open in new window




Thoughts?
0
Hi expert,


How to connect ftp/sftp using jQuery?

Or do you have any other suggestion how to connect ftp/sftp?
0
Technology Partners: We Want Your Opinion!
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Bootstrap validator trying to validate the form and submit to the database. The validation part works but it does not submit

the link is here https://jsfiddle.net/tsomik1/5cu96c6y/10/
0
How can I dynamically remove options from a select list based on class?

I have tried jquery  $(".myClass").remove() and $(".myClass").hide(); and neither worked.

Thanks.
0
I had this question after viewing Anyway to format this array data differently?.

I've been at this for two hours now! it can't be that hard. I'll keep at it but I hope someone can help me...

 The solution in link above works and you can see the JSFiddle Husyein did here

https://jsfiddle.net/5t10qr3c/

My data has changed and I've added one more value to it. I just need to change the "str" and how it's contacted and add the new value.

My new data looks like this. Please note the "computedvalue". I also added "RowId" thinking this might help.
var data = [{
  RowId: 1,
  name: "county1",
  rank: 333,
  year: 2015,
ComputedValue: 2.8
}, {
  RowId: 2,
  name: "county2",
  rank: 2302,
  year: 2015,
ComputedValue: 3.7
}, {
  RowId: 3,
  name: "county1",
  rank: 144,
  year: 2014,
ComputedValue: 5.9
}, {
   RowId: 4,
  name: "county2",
  rank: 123,
  year: 2014,
ComputedValue: 8.4
}];

Open in new window



In the Fiddler above, how can I change this section to add an array of "computedvalue"?

if (that.name != this.name) {
      str += ']}{"name": "' + this.name + '", "data ": [' + this.rank;
    } else {
      str += ', ' + this.rank;
    }
  } else {
    str += '{"name": "' + this.name + '", "data": [' + this.rank;
  };

Open in new window


 I tried this but it breaks the "data" part of the string

I first changed the "_,chain" to this

var newdata = _.chain(data).sortBy("rank").sortBy("ComputedValue").sortBy("year").value();

Open in new window


Tried these 2

str += str += '{"name": "' + this.name + '", "data": [' + this.rank + '", "ComputedValue: ['+ this.ComputedValue

str += str += '{"name": "' + this.name + '", "data": [' + this.rank + ']' + ' ", "ComputedValue": [' + this.ComputedValue;

Open in new window


So, I want it to look like this. I have the original "data"...I wonder if I can push it into the final json below?

{"name": "county1", "data": [144, 333], "ComputedValue": [5.9,2.8]}{"name": "county2", "data ": [123, 2302], "ComputedValue": [8.4, 3.7]}
0
Hello experts,

I am trying to call the ajax function only if there are values in 'stepname' and 'altmethod' else show and alert. When I include the following code, the else part gets executed all the time though there are no values. Could anyone kindly help me with this.

$(document).on("click", '#nextstep', function(e) {

    e.preventDefault();
 var stepname = $('#stepname').val(); 
 var chosen_altmethod = $('#chosen_altmethod').val();
 var altmethod = $('#altmethodname').val();

 
var formData = new FormData();
formData.append('stepname',stepname);
formData.append('altmethod',altmethod);
formData.append('chosen_altmethod',chosen_altmethod);
 formData.append('action','nextstep');

 console.log(stepname,"stepname");
console.log(altmethod, "altmethod");
console.log(chosen_altmethod,"chosen_altmethod");

if((stepname=="undefined") && (altmethodname=="undefined")){
  alert('please choose a step');
}else{
        $.ajax({
             type: 'POST',
            url: "<?= base_url() ?>index.php/variants/fetchstep1/",
             data: formData,
             processData: false,
      contentType: false,
             success: function (data) {

   $("#steplist").remove();
 $("#replacelist").html(data);
   $('html, body').animate({ scrollTop: 0 }, 0);
             }
         });
}
     });

Open in new window


Thank you in advance
0
Hello Experts,
I am still struggling with this issue.  Here is my sample mock up code.   When I click on the Save button, it scrolls to the top of the screen for a moment and returns to the same position.

I had this question after viewing Force page scroll position to top at page refresh in ASP.Net.

Below is the code.

Thank you very much in advance!



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    <script>
        function ToTopOfPage() {
            window.scrollTo(0, 0);
        }
    </script>


</head>
<body>
    <form id="form" runat="server">
        <div id="content">
            <div class="form_table">
                <table>
                    <tr>
                        <div id="wrapper">

                            <div id="header">
                                <div id="nav"><a href="index.html">Home</a> | <a href="#">About Me</a> | <a href="#">Contact Me</a> | <a href="#">My Photos</a> | <a href="#">My Videos</a></div>
                                <div id="bg"></div>
                            </div>

                            <div id="left-column">
     …
0
I am trying to validate using remote options, but it is always validate as failed
<div class="row">
										<div class="col-sm-12 col-xs-12">
											<input type="text" name="userName" placeholder="Username" class="form-control input-lg" required="required" data-bv-remote="true"/>
										</div>
									</div>

Open in new window

 userName: {
                message: 'The username is not valid',
                validators: {
                    notEmpty: {
                        message: 'The username is required and can\'t be empty'
                    },
                    stringLength: {
                        min: 6,
                        max: 30,
                        message: 'The username must be more than 6 and less than 30 characters long'
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9_\.]+$/,
                        message: 'The username can only consist of alphabetical, number, dot and underscore'
                    },

                    remote: {
	                    url: '/includes/website.cfc?method=checkusername',
	                    message: {
	                        en_US:  "This usenrame is already taken, please choose another one",
	                    },
	                    data: {
	                        type: 'userName'
	                    },
	                    type: 'POST',
	                    delay: 1000
	                }


                }
            },

Open in new window

<cffunction name="checkusername" output="true" returntype="any" access="remote" returnformat="JSON" >
          <cfargument name="username" required="true" type="string" />
          <!--- set the default value to false --->
          <cfset var emails = StructNew() />
          <cfset emails.valid = "false" />


          <!--- code to check email in system --->
          <cfquery name="findemail" datasource="#request.datasource#">
               select username
               from users
               where username = <cfqueryparam  value="#arguments.username#" cfsqltype="cf_sql_varchar" />
          </cfquery>
          <cfif findemail.RecordCount eq 0>
               <cfset emails.valid = "true" />
          </cfif>
          <cfoutput>#SerializeJSON(emails)#</cfoutput>
     </cffunction>

Open in new window

0
Here's my code:

['code]<html>
<head>
<title>Health Summary</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<style>
 
body {
font-family: Arial, Helvetica;
font-size:12pt;      

}

.button-verify {
      width:150px;
      background-color:#000000;
      border-radius:10pt;
      padding:10px;
      text-align:center;
      box-shadow:10px 10px 5px #cccccc;
      height:25px;
      color:#ffffff;
}

</style>

<script>
$(document).ready(function() {
      
      function isValidDate(dateString) {
            // First check for the pattern
            if (!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString))
            return false;

            // Parse the date parts to integers
            var parts = dateString.split("/");
            var day = parseInt(parts[1], 10);
            var month = parseInt(parts[0], 10);
            var year = parseInt(parts[2], 10);

            // Check the ranges of month and year
            if (year < 1000 || year > 3000 || month == 0 || month > 12)
            return false;

            var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

            // Adjust for leap years
            if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
            monthLength[1] = 29;

            // Check the range of the day
            return day > 0 && day <= monthLength[month - 1];
            };

            function isInt(value) {
                return !isNaN(parseInt(value, 10))
            && (parseFloat(value, 10) == parseInt(value, 10));
            }
      
      function validateForm() {
            var dob = document.getElementById("usrDOB");
            var ssn = document.getElementById("usrSSN");
            var …
0
I had this question after viewing Anyway to format this array data differently?.

The solution in my question above works. You can see it in this JSFiddle that  Huseyin create here https://jsfiddle.net/5t10qr3c/

You see the string output is like this: {"name": "county1", "data": [144, 333]}{"name": "county2", "data ": [123, 2302]}

I actually need this in an array like this: For example array of 2
[Object, Object]
0: Object
    data: Array(2)
              0: 144
              1:333
     name: "county1"
1: Object
   data: Array(2)
             0: 123
             1: 2302
   name: "county2"

I tried these
I used "split" but that won't work

I thought just wrapping the "str" with [] would do it but no, it's still a  string.

I'm thinking as the string is being build, I need to push it into an array? but not sure.
0
1. I have an array and the data looks like below

 var seriesTest  =[];
 var ret = <I get the data from database with C# code>;

 for (var = i=0; i < ret.length; i++)
{
    seriesTest.push({ "name":ret[i].countyName, "rank": ret[i].rank, "year":ret[i].year  });
}

console.log(seriesTest);

Open in new window


2. The data looks like this
 0: Object
      name: "county1"
      rank: 333
      year: 2015

 1: Object
       name: "county2"
      rank: 2302
      year: 2015

 2: Object
       name: "county1"
      rank: 144
      year: 2014

 3: Object
       name: "county2"
      rank: 123
      year: 2014

Open in new window


3. You see the there are 2014 and 2015 years. There are two "county" names...county1 and county2. You see the "rank" as well
For the "data", I want the earliest year (2014) and then 2015
[
{"name": "county1", "data": [144,333]},
{"name": "county2", "data": [123,2302]},
];


Anyway to do this in Javascript?
0
Webinar: Aligning, Automating, Winning
Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Hello
I have a strange problem which I have been trying to solve for hours. I have declared a global variable and am using it to get the value of an item in jqxgrid. However, what is happening is that on the first click, no items are displayed, on the 2nd click it displays the result from the first click and so on with future click showing the previous click result.

I would be grateful if someone could help with this and point out my error. Many thanks

<script type="text/javascript">
					
     var items = '';
					
</script>

Open in new window


// START OF ACTION CODE ON CLICK WITH NO POPUP
buttonclick: function(row) {
  $.confirm({
    theme: 'modern',
    title: 'Delete Item',
    content: items, <---- TRYING TO DISPLAY VALUE HERE
    icon: 'fa fa-question-circle',
    animation: 'scale',
    closeAnimation: 'scale',
    opacity: 0.5,
    buttons: {
      'confirm': {
        text: 'Proceed',
        btnClass: 'btn-blue',
        action: function() {
          $.confirm({
            theme: 'modern',
            title: 'This action is critical',
            content: 'Critical actions Cannot be undone. Proceed with caution',
            icon: 'fa fa-warning',
            animation: 'zoom',
            closeAnimation: 'zoom',
            buttons: {
              confirm: {
                text: 'Sure!',
                btnClass: 'btn-orange',
                action: function() {
                  //$.alert('A very critical action <strong>triggered!</strong>');
     

Open in new window

0
Hi Expert,

In a ASP page this is normally not a problem but jquery mobile seems to make this a little harder.
I'd like to load a popup from a jquery mobile page and fill in a form, submit it, store my value into a DB (left out in my example file) and then close the popup and refresh the initial index.html page.  

<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Cache-Control" content="no-store" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/themes/default/jquery.mobile-1.4.5.min.css">
<script src="../js/jquery/jquery.js"></script>
<script src="../_assets/js/index.js"></script>
<script src="../js/jquery/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="main" id="ui-content" class="ui-content">
<a href="#popupnieuw" data-rel="popup" data-position-to="window" data-transition="pop"  data-mini="true" data-inline="true" data-theme="b" data-corners="true" data-shadow="true" data-wrapperels="span" class="ui-btn ui-btn-inline ui-icon-plus ui-btn-icon-left">Een onderwijs behoefte toevoegen</a>
<div data-role="popup" data-history="false" id="popupnieuw" data-dismissible="false" data-overlay-theme="b" data-theme="a" data-corners="false" data-tolerance="15,15">
<div data-role="header" data-theme="a">
<a href="#" data-rel="back" data-role="button" data-theme="a" data-icon="delete" data-iconpos="notext" data-position-to="window" class="ui-btn-right">Close</a>
<h1>Een nieue wens</h1>
</div>			

Open in new window

0
How can I do a loop and change file names a long with it.   I have the current code that works if i want to loop and print out the img src line 10 types.

But i am unsure of how to loop through, and print out the img src and change the file name as well.

For example first loop would print out

img src="http://test.co/media/img/1.png
next loop will print out
img src="http://test.co/media/img/2.png
next loop will print out
img src="http://test.co/media/img/3.png
and so on un till  img src="http://test.co/media/img/10.png

my guess would be  something like this    img src="http://test.co/media/img/" + HTMLstring[i] + ".png"
but it doesn't seem to work. Or i can be totally off.   Thanks for any help in advance.

var HTMLstring = "";
            for(var i = 0; i < 10; i++){
                HTMLstring += '<img src="http://test.co/media/img/1.png">'
            }
0
Having a problem with getting fn2 to fire after fn1.  I am sure it is because the google call is asynchronous but not sure how to resolve.

Sample here

    function fn1(searchMethod, searchValue) {
        $.ajax({
            url: 'https://maps.googleapis.com/maps/api/geocode/json?' + searchMethod + '=' + searchValue + '&key=someGoogleKey',
            dataType: 'json',
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
            },
            success: function(googleData, searchMethod) {
                alert('google done');
                console.log(googleData);
            }

        }).done(function(locData) {
            dfd.resolve();
        });
    }

    function fn2() {
        alert('second function')
    }

    var dfd = $.Deferred();
   
    (function() {
        //function one passes 2 parameters
        //in this case address telling to search for the New York ZIP 12345
        $.when(fn1('address', '12345')).done(function() {
            fn2();
        });

    })();
0
This form validation code works:

function validateForm() {
	var dob = document.getElementById("usrDOB");
	var eeid = document.getElementById("usrEEID");
	var error = '';
	if (!isValidDate(dob.value)) 
	{
		$('#usrDOB').css('border', 'solid 2px red').focus();
		error = "Date of Birth must be in the format XX/XX/XXXX\n\r";
	} 
	else 
	{
		$('#usrDOB').css('border', '');
	}
	if (eeid.value.length==0) 
	{
		$('#usrEEID').css('border', 'solid 2px red').focus();
		error = error.concat("Be sure to enter your spouse\'s Employee Id.");
	}
	if (error.length > 0) {
		alert(error);
		return false;
	}
	return true;
}

Open in new window


This doesn't...

function validateForm() {
	var dob = document.getElementById("usrDOB");
		
	if (!isValidDate(dob.value)) 
	{
		$('#usrDOB').css('border', 'solid 2px red').focus();
		alert("Date of Birth must be in the format XX/XX/XXXX\n\r");
	} 
	else 
	{
		$('#usrDOB').css('border', '');
	}
	
	var eeid = document.getElementById("usrEEID");
	var error = '';
	//alert(eeid.value);
	if(eeid.value.length==0)
	{
		$('#usrEEID').css('border', 'solid 2px red').focus();
		alert("Please enter your Member Id!");
	}
	else
	{
		var myString = eeid.value;
		var stringCheck = "sp";
		var foundIt = (myString.lastIndexOf(stringCheck) === myString.length - stringCheck.length) > 0;
		if(foundIt==false)
		{
			alert("Be sure to include \"sp\" after your Employee Id.");
			$('#usrEEID').css('border', 'solid 2px red').focus();
		}
		else
		{
			$('#usrEEID').css('border', '');
		}
	}
}

Open in new window


Why?
0
Hi All,
Advance thanks!
I am using ASP.NET MVc core and jqgrid in the ui. I receive both date string (Last Update) and actual date field (DocumentSubmissionDate). I need date field only, i added in the view to take snapshot to display here.  My issue is i need to display date field just like that string date (i.e. mm/dd/yyyy by remove T and show AM/PM). Please find the script below

<script type="text/javascript">
    $(document).ready(function () {
        var $DocumentData = $('#jqgClaims');

        $(window).bind('resize', function () {
        //$("#jqgClaims").setGridWidth($(window).width() / 1.03);
        //$("#jqgClaims").setGridWidth($(window).width() / 1.47);
        jQuery("#jqgClaims").setGridWidth($('#parentDiv').width() - 10, true);
    }).trigger('resize');

        $DocumentData.jqGrid({
            url: '@Url.Action("GetDocumentList", "wsApproval")',
            datatype: 'json',
            mtype: 'POST',
            cmTemplate: { align: 'left' },
            colNames: ['Claim No', 'Doc No', 'Document Name', 'Document Status', 'Last Update','DocumentSubmissionDate', 'Supervisor Id', 'Examiner Id', 'Reassign Id','test' , 'DocumentTypeCode'],
            colModel: [
                        { name: 'ClaimNumber', align: 'left', search: false, hidden: false, width: '80%' },
                        { name: 'DocumentNumber', align: 'left', search: false, hidden: true, width: '80%' },
                        { name: 'DocumentTypeName', …
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