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 am using the select2 drop down list for states. The problem I have is that when you tab over to it, it doesn't allow you to type in a letter to go straight to the state in the list. Yes, you can hit Enter to open it up, but I'd like it to work as the select normally does by default.

Here is my code:

$('.ddlState').select2({
placeholder: '[Select]',
matcher: function (params, data) {
    return matchStart(params, data);
    },
width: 'resolve',
selectOnClose: true
});

Open in new window


I have checked their examples to see if it's possible and find one here under Multi-select boxes (pillbox). but I'm thinking maybe that's only if I change it to multiple, which I do not want. I viewed source code and see nothing in there that would indicate an option to hot key. Don't be fooled by the first example on their page, that's what the select box looks like by default before they turn it into a select2 box.
https://select2.org/getting-started/basic-usage

It appears this just doesn't have that ability, which is too bad if it doesn't, because that makes it unusable.

If you know of a way, please share!

thanks!
0
I have the code where i want to return the true/false and because i am using that function somewhere else to see if i get false, do this else do nothing

this is my code and it is giving me callback is not defined

function CheckIfPaused(callback) {
	$.post('/cfc/cfc.cfc?method=check',{id: $('body').attr('data-id')}, function(data) {
		if(data.status == 1) {
			callback('true');
		}else {
			callback('false');
		}	
	},'json');
}

Open in new window


$document.ready(function() {
if(CheckIfPaused() == false) {
do this 
}
});

Open in new window

1
After the ajax post is success, how can i reload html div id = resultlist?
This ajax call is to add a record into the database.

<script>
                                   function AddNew(fleetid, feeDescription, priceType, cost)
                                   {
                                       $.ajax({
                                           url: "/Home/AddFeePrice",
                                           datatype: "json",
                                           data:
                                           {
                                               'feedescription': document.getElementById(feeDescription).value,
                                               'pricetype': document.getElementById(priceType).value,
                                               'cost': document.getElementById(cost).value,
                                               'stage': 'Active',
                                               'fleetId': document.getElementById(fleetid).value
                                           },
                                           type: "POST",
                                           success: function (data) {
                                               var result = data.updateFeeStatus;
                                               alert("Success " + result);
                                            },
                                           error: function (error) {
                                    

Open in new window

0
I have this piece of code where i am trying to validate the jquery based Date of Birth Validation.

is there any JS function which also checks the full date if it falls in a leap year or not, i am trying this but it does seems to be working

function isValidDate(s) {
  var bits = s.split('/');
  var d = new Date(bits[2] + '/' + bits[1] + '/' + bits[0]);
  return !!(d && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[0]));
}

Open in new window


date i tested is: 02/29/1920 - it is giving false (edited)

testing it like this:

    function init_inputOnKeyUp(){
        $('select[name="day"],select[name="year"]').off('change');
        $('select[name="month"],select[name="day"],select[name="year"]').on('change', function(e) {
        if (type == 'select') {
            var newdate = $('select[name="month"]').val() + '/' + $('select[name="day"]').val() + '/' + $('select[name="year"]').val();
                        var results = isValidDate(newdate.toString());
                        console.log(results);
                        console.log(newdate.toString());
        }
        });
}

Open in new window


problem i can't use any extra library like moment.js

the error is it is always giving me false when i try to validate with a full date

i am not sure at this point, if the error is happening on leap year or onchange issue
1
getDeals();

    setTimeout(function () {
        timelineController();
    }, 300);

    createDefaultProps();
    loadSocialData();
  
    
    loadLeadData();

    loadActData();
    getJr();
    getJrTimeline();

Open in new window


here is my list of functions which each has a ajax function, how do i tell these functions to wait until ajax is complete ? and run in order
1
I have a side project that I want to rewrite on my own time. I want to use ASP.Net Core and Angular as front end.

I'm reading about the latest version of Angular https://angular.io/guide/releases

Is it Angular 7 but the stable version is 6?
0
Hello everybody,

I have a bunch of AJAX scripts that fetch and give data from and to PHP but the one I'm trying to make, I have no idea how to do it or which is the best way to do it. Here's the scenario:

  1. User selects 1st option form combo box and second combo box gets filled (AJAX)
  2. User selects 2nd option from second combo box and a table with check boxes appears at the bottom (AJAX)
  3. User selects/un-selects options (check boxes), hit SAVE and it supposedly saves the changes into the DB using AJAX and PHP

The problem is that the table rows with its check boxes are generated dynamically. Normally I would iterate through all the check boxes creating variables which would be passed as POST to a PHP function in another page using AJAX but, since in this case the check boxes are created dynamically I can't do that as I don't know the number of variables (check boxes) I will have to deal with or their IDs.

I've made a function in jQuery to fetch all check boxes generated in PHP and sent to the page and got this:

<input type=​"checkbox" data-render=​"switchery" id=​"author-11" name=​"author-11" data-theme=​"default" checked>​
<input type=​"checkbox" data-render=​"switchery" id=​"author-12" name=​"author-12" data-theme=​"default" checked>​
<input type=​"checkbox" data-render=​"switchery" id=​"author-13" name=​"author-13" data-theme=​"default" checked>​
<input type=​"checkbox" data-render=​"switchery" 

Open in new window

0
HI Experts,

I have a child theme based on Appointment Pro that I am using on www.atlas365.ca

As you can see, in mobile view I have a burger menu, but how can I make the burger menu appear in tablet view as well, in order to avoid the menu overlap the logo?

Thank you,
0
I have asmx and I hope to have html / jquery to consume it.
The asmx below using class library as parameter.

I do not know how to consume it on html/jquery. Can you show me how to do that?

Thanks,


[WebMethod]
        public string CreateDisciplinaryComplaintInPDF(Domain.DisciplinaryComplaint dd)
        {
            Controller.PDFservice ps = new Controller.PDFservice();
            Domain.DisciplinaryComplaint ddNew = new Domain.DisciplinaryComplaint();
            #region data mapping
            ddNew.fullName = dd.fullName;            
            #endregion
            string returnString =  ps.GetDisciplinaryComplaintDownloadData(dd);
            return returnString;
        }

Open in new window

0
I'm running in to some difficulty loading an HTML file into a DIV using JQuery 3.x's load() method:

http://api.jquery.com/load/

Although I am successfully able to load and display the HTML file, .. I am getting JavaScript errors, which I'd like to eliminate/suppress.

I have this very simple JS function to trigger the loading of the HTML file:

function loadGoogleMapView(pageurl) {
	$("#myMap").load(pageurl);
}

Open in new window


.. and then I am calling the method by passing the HTML filename to it:

<a href="#" onclick="loadGoogleMapView('map-view.html');">View Map</a>

Open in new window


The contents of the HTML file that I'm trying to load is as follows (note that I have deliberately stripped out my Google Maps API key).

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

<style>
	#mapView { position: absolute; top: 0; right: 0; bottom: 0; left: 0; }
</style>	

</head>

<body>

<div id="mapView"></div>

<script>
function initMap() {
	var broadway = {
		info: '<strong>Chipotle on Broadway</strong><br>\
					5224 N Broadway St<br> Chicago, IL 60640<br>\
					<a href="https://goo.gl/maps/jKNEDz4SyyH2">Get Directions</a>',
		lat: 41.976816,
		long: -87.659916
	};
	var belmont = {
		info: '<strong>Chipotle on Belmont</strong><br>\
					1025 W Belmont Ave<br> Chicago, IL 60657<br>\
					<a href="https://goo.gl/maps/PHfsWTvgKa92">Get Directions</a>',
		lat: 41.939670,
		long: -87.655167
	};

Open in new window

0
I'm having a problem with iterating through a class in Jquery...
The $(allmessages).each(function (i, obj) ... is not executing for every <span> with the class of '.encryptedtext'

It hits the first message, decrypts it perfectly, but then doesn't execute the code on the next span.
I verified that the class is present on every span where the encrypted messages exist using 'inspect' feature in Chrome.

            function (data) {


                var ServerResponse = String(data);
                ServerResponse = unescape(ServerResponse);
                //alert(ServerResponse);
               $(".divinner").html(ServerResponse);
               // $(".divinner").append(ServerResponse);
                var allmessages = $('.encryptedtext');
                $(allmessages).each(function (i, obj) {
                    //test
                    var encryptedtext = $(obj).html();
                    encryptedtext = encryptedtext.replace(' ', '+');
                    //alert('message recieved encrypted: ' + encryptedtext);
                    //alert('message unescaped: ' + unescape(encryptedtext));
                    //alert('channel id and key: ' + channelid + key);

                    var decryptmsg = decrypt(encryptedtext, channelid + key);
                    alert('message decrypted:' + decryptmsg.toString(CryptoJS.enc.Utf8));
                    var plaintxt = decryptmsg.toString(CryptoJS.enc.Utf8);
                    var tempobj = obj;
                    

Open in new window

0
I'm working in Symfony and attempting to implement a JQuery post dynamic.

I found an example that's currently working in the existing code, but I'm new enough to Symfony where it took me a while to figure out the routing configuration and even though I've been able to trace the logic, I'm still scratching my head.

Here's the first part of the JQuery code:

$.post('/admin/sites/' + psID + '/pages/' + ppID  + '/update', form, function(res){

Here's the routing located on the "routing_admin.yml" file:

admin_page_update:
    path: /sites/{psID}/pages/{ppID}/update
    defaults: { _controller: AppBundle:Page:update }

Mystery solved!

But, here are my questions:

How does Symfony keep track of all the various routing pages. In the tutorial that I've taken, there was only one routing file in the config file. How does Symfony keep all of these organized?

In the path above, "admin" is not referenced despite the fact that it is referenced in the JQuery code. How does Symfony know to process...

$.post('/admin/sites/' + psID + '/pages/' + ppID  + '/update', form, function(res)

as...

admin_page_update:
    path: /sites/{psID}/pages/{ppID}/update
    defaults: { _controller: AppBundle:Page:update }

...when "admin" is not referenced in the path? I'm thinking "path" should look like this:

admin_page_update:
    path: /admin\/sites/{psID}/pages/{ppID}/update
    defaults: { _controller: AppBundle:Page:update }

Thanks!
0
I have a checkbox that enables and disables the validation of a textbox when checked. I am doing this on client side and want everything to be on client side.

I am attempting to use jquery to accomplish what I need to do. I have written most of the code already and it works mostly how I want it to, except for when I first activate the textbox it throws up the validation error. I only want it to validate on submission.
textboxval.PNG
Here is my code:
    var idEmail = {
        txtEmailNotification: "<%= txtEmailNotification.ClientID %>"
    }
    var idEmailVal = {
        valRegExpEmailNotification: "<%= valRegExpEmailNotification.ClientID %>"
    }
    var idEmailReqVal = {
        valEmailNotification: "<%= valEmailNotification.ClientID %>"
    }
$(document).ready(function functionCheckEmail() {
    //check if checkbox is checked on page load
    if ($('#chkIsEmailNotices').is(':checked')) {

        $("#" + idEmail.txtEmailNotification).show(); //shows if checked
        ValidatorEnable($("#" + idEmailVal.valRegExpEmailNotification)[0], true); //shows validators
        ValidatorEnable($("#" + idEmailReqVal.valEmailNotification)[0], true); //shows validators

    } else {

        $("#" + idEmail.txtEmailNotification).hide(); //hides if not checked
        ValidatorEnable($("#" + idEmailVal.valRegExpEmailNotification)[0], false); //hides validators
        ValidatorEnable($("#" + idEmailReqVal.valEmailNotification)[0], false); //hides validators
    }

Open in new window

0
I am currently trying to set up a notifications settings page where users can opt in for text message or email notifications.

I have a page where if the user clicks a checkbox, a textbox will appear so they can fill out their contact information. I want the textboxes to validate the information. I want the validations and the checkbox hiding and showing the textbox to be client side.

I am using jquery to hide and show the textboxes, and to check the validations when the checkbox is checked. Currently, most everything is working, except when the checkboxes are unchecked. It shouldn't validate the textbox if it's empty and hidden(checkbox unchecked), but it does.

Here is the jquery I am using:
<script type="text/javascript">
$(document).ready(function () {
    //Must have these for nonstatic ids
    var idText = {
        txtTextNotification: "<%= txtTextNotification.ClientID %>"
    }
    var idTextVal = {
        valTextNotification: "<%= valTextNotification.ClientID %>"
    }
    var idEmail = {
        txtEmailNotification: "<%= txtEmailNotification.ClientID %>"
    }
    var idEmailVal = {
        valRegExpEmailNotification: "<%= valRegExpEmailNotification.ClientID %>"
    }

    //check if checkbox is checked on page load
    if ($("#chkIsTextable").is(':checked')) {

        $("#" + idText.txtTextNotification).show(); //shows if checked
        ValidatorEnable($("#" + idTextVal.valTextNotification)[0], true); //shows validators

    } else {
        

Open in new window

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

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

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

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

Open in new window

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

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

Open in new window

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

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

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

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

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


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

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

Open in new window

0
we use suitecrm and we also have simple landing page written in mvc net.

we want to see code example how to call the api module e.g.
lead list.

thanks
0
Hello everybody, hope you had a wonderful start for 2019.

I'm having problems with a jQuery/AJAX + PHP autofiller. I'm trying to fetch all the posibble results for the users in my DB, no matter what the user search for (could be username, name or last name). So far I've managed to fetch everything from my DB using PHP with the following script:

$sql
=
"
SELECT user_id, apellido, primer_nombre, nombre_usuario
FROM dbo.v3_usuarios
WHERE (nombre_usuario LIKE :parte_usuario)
OR (primer_nombre LIKE :parte_usuario2)
OR (apellido LIKE :parte_usuario3)
"
;

try
{
	
	$parte_usuario = '%' . strval($parte_usuario) . '%';
	
	$core = Core::getInstance();
	$stmt = $core->dbh->prepare($sql);
	$stmt->bindParam(':parte_usuario', $parte_usuario, PDO::PARAM_STR);
	$stmt->bindParam(':parte_usuario2', $parte_usuario, PDO::PARAM_STR);
	$stmt->bindParam(':parte_usuario3', $parte_usuario, PDO::PARAM_STR);
	
	if ($stmt->execute())
	{
		
		$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
		
		$usuarios = array();
		
		foreach ($result as $key => $value) {
			
			array_push($usuarios, $value['user_id'], $value['apellido'], $value['primer_nombre'], $value['nombre_usuario']);
			
		}
		
		echo json_encode($usuarios);
		
	} else { echo 'Couldn\'t connect to DB'; }

	$stmt = null;
	$core = null;

} catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); }

Open in new window

And I've managed to fetch it using AJAX with:

$('#usuario-buscar').typeahead({
	source: function (query, result) {
		$.ajax({
			url: "somepage.php",
			data: 'query=' + query,            
			dataType: "json",
			type: "POST",
			success: function (data) {
				// console.log(data);
				result($.map(data, function (item) {
					return item;
					//console.log(item);
				}));
			}
		});
	}
});

Open in new window

This is taken from an example in phppot.com and I can make it work with only one field, but I would like to show the results like "USERNAME - Lastname Fisrtname".

Any chance to get help with this? All the tries I've made repeat tens of times each result in the "dropdown" it creates for the textbox.

BTW the user_id, while I don't want it displayed in the auto fill dropdown, will be used to populate some hidden text box or something for the form to grab.

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

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

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

Open in new window

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

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

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

Open in new window

1
Is Jquery outdated? what's the new technology that has replaced JQuery? Is it Bootstrap, Angular or React?

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

Thanks for the info.
1
When I run the html file, it is fine  for the ADD and Remove, But when I run the asp page, the image won't be added. per the code:
 <table>
  <tr>
    <td> 
     
          
   <div class="p">
          <div class="thumbnail">
            <div class="thumbnail-img-<%# DataBinder.Eval(Container.DataItem, "idProduct") %>">
        <a href="product.aspx?id=<%# DataBinder.Eval(Container.DataItem, "idProduct") %>">
          <div class="img-p">
            <img class="thumbnail-img-<%# DataBinder.Eval(Container.DataItem, "idProduct") %>" src="<%=LINK_IMAGES%>small/<%# DataBinder.Eval(Container.DataItem, "idProduct") %>.jpg">            
          </div>
        </a>
        
        <p><button class="btn add-remove-btn btn-primary" data-identitfier='4'>Add to List</button>
              </p>
      </div>
    </td>
  </tr>   
    
	
    </table>
    

Open in new window

1
I have an MVC C# Web Application and am using jQuery Bootgrid. The bootgrid is populating fine, the issue is there is a toggle button on the upper right of the grid that allows the user to select which columns in the grid are to be present. This feature is turned on with the following code "columnSelection: true". The issue is the button is not allowing the user to select the fields as it should. I have attached screen shots of how the button is supposed to function. When running through google dev, an error is thrown saying that it cannot find popper.js:1 Failed to load resource; however I have a reference to it (See Script Links below). Maybe it is the order of which I am loading. I have no idea at this point. Thanks.

Grid Snippet ---------------------------------------
    <script>
        var grid = $("#grid-data").bootgrid({
            ajax: false,
            caseSensitive: false,
            columnSelection: true,
            formatters: {
                "commands": function (column, row) {
                    return "<button type=\"button\" class=\"btn btn-xs btn-default command-edit\" data-row-id=\"" + row.product_id + "," + row.client_id + "," + row.product_name + "," + row.description + "," + row.active + "\"><span class=\"fas fa-pencil-alt\"></span></button> " +
                        "<button type=\"button\" class=\"btn btn-xs btn-default command-delete\" data-row-id=\"" + row.product_id + "\"><span class=\"fas fa-trash-alt\"></span></button>";
  …
1

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