Jquery

Length of string

`$('el').val().length`

Ajax

Simple request

$.ajax({
    url: "test.html",
    cache: false,
    success: function(html){
        $("#results").append(html);
    }
});

Post request with data

$.ajax({
url: "test.html",
cache: false,
type: "POST",
data: {id : menuId}
success: function(html){
    $("#results").append(html);
}
});

Optionally do other stuff:

...

request.done(function(msg) {
    $("#log").html( msg );
});

request.fail(function(jqXHR, textStatus) {
    alert( "Request failed: " + textStatus );
});

Setting up the page

    $(document).ready(function() {
    //stuff
    });

Avoiding Conflict

Jquery.noConflict();

removes the $() shortcut and replaces with Jquery()

Forms

Checkbox

$('.checkbox').click (function(){
    var thisCheck = $(this);

    if ( thischeck.is(':checked') ) {
        // Do stuff
    }
});

Submitting forms

$('#form_id').on('submit',function (e) {

    e.preventDefault();

    // do more stuff

  });

Getting Forms

$('#form2').find('input[name=name]');
$('#form2').find('#email');

Get text box

var bla = $('#txt_name').val();

Set text box

$('#txt_name').val('bla');

Focus Input field

$('#inputname').focus();

Submitting on forms that don't yet exist

What's happening? We're binding to #form_container which does exist, then delate to #form_id to trigger when that does exist)

$('#form_container').on('submit','#form_id', function (e)) {

  e.preventDefault();

    // do more stuff

});

What version of jQuery?

$().jquery; or $.fn.jquery;

How do I select mutliple classes?

<p class="a b"> $('.a.b') this is an inersection <p id="z" class="a b"> $('#z.a.b') this is an inersection

<p class="a"><p class="b"> $('.a .b') search for a and then any descendents with .b

OR

$('.a').filter('.b'); this is slower as it builds a list of objects with class a first and then

Load data from external template

$.get('/url/', function(data){ 
  $(data).find("#id_to_find").appendTo("#id_to_append");
});

Prevent a clicks going anywhere

    e.preventDefault();
    e.stopPropagation();

What's happening? stopPropagation stops the event from bubbling up the event chain, and preventDefault prevents the default action the browser makes on that event.

Difference between return false and preventDefault

function() {
  return false;
}

// IS EQUAL TO

function(e) {
  e.preventDefault();
  e.stopPropagation();
}

more here

Checking Div is empty

if( $('#leftmenu').is(':empty') ) if( $('#leftmenu:empty').length )

Setting data attributes

html

 <div id="mydiv" data-myval="10"></div>

get the data

var a = $('#mydiv').data('myval'); //getter

set the data

$('#mydiv').data('myval',20); //setter

One liners!

What How
Selecting tag name $("li").text("new list item") <ol><li></li><li></li></ol>
class selector $(".class").text("new text")
Id selector $('#id').text('new text')
Add class $(".class").css("display","block");
Remove Class $(".class").css("display","none");
Replacing Html $( "div.demo-container" ).html();
Referencing textara content_textarea.val() (don't use content_textarea.text() as that will load the oriiginal text
Get glassname of div $('.myclass').attr('class');
Remove class $('#mydiv').removeClass('colors');
Remove all classes $('#mydiv').removeClass();

TO do

Basic Selectors

  • Matches any element. E Matches all elements with tag name E. E F Matches all elements with tag name F that are descendants of E. E>F Matches all elements with tag name F that are direct children of E. E+F Matches all elements with tag name F that are immediately preceded by a sibling of tag name E. E~F Matches all elements with tag name F that are preceded by any sibling of tag name E. E:has(F) Matches all elements with tag name E that have at least one descendant with tag name F. E.c Matches all elements E that possess a class name of c. Omitting E is identical to .c. E#i Matches all elements E that possess an id value of i. Omitting E is identical to #i. E[a] Matches all elements E that posses an attribute a of any value. E[a=v] Matches all elements E that posses an attribute a whose value is exactly v. E[a^=v] Matches all elements E that posses an attribute a whose value starts with v. E[a$=v] Matches all elements E that posses an attribute a whose value ends with v. E[a*=v] Matches all elements E that posses an attribute a whose value contains v.

http://refcardz.dzone.com/refcardz/jquery-selectors

Positional Selectors

Custom Selectors

CSRF

To prevent cross-site request forgery you need to add a token to the html page to prevent a malicious website submitting a form

Add token to meta tag in head

Load into jquery

$.ajaxSetup({ headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') } });

Accessing from Laravel

Request::header('x-csrf-token');

Dynamically loading scripts

$.getScript('/path/to/imported/script.js', function()
{
  // script is now loaded and executed.
  // put your dependent JS here.
  // what if the JS code is dependent on multiple JS files? 
});

more

Wildcards

 $('[id^=pick_]').click(
function(event) {

    // Do something with the id # here: 
    alert('Picked: '+ event.target.id);
    // $(this).attr("id")

}

);