JQuery snippets

Adding text to a span using jquery


$("#spanid").text("Your text here");

Adding html to a span using jquery


$("#spanid").text("HTML here");

Append html to a span using jquery


$("#spanid").append("HTML here");

Check/uncheck a checkbox input or radio button


$("#x").prop("checked", true);
$("#x").prop("checked", false);

Check checkbox checked property


$("#x").is(':checked')

Handle change of checkbox


$('#x').change(function() {
   if($(this).is(":checked")) {
      //'checked' event code
      return;
   }
   //'unchecked' event code
});

Make a dropdown disabled using jquery
If you work with a form, the disabled fields does not submit, so use a hidden field to store disabled dropdown value.


$('#dropdown').attr("disabled", "disabled"); 
$('#dropdown').removeAttr("disabled"); 

Get selected text from drop down list


$("#yourdropdownid option:selected").text();

increase the opacity of div


$(div).css({opacity : 0})
$(div).animate({'opacity': 1}, 1000);

$('div').fadeTo('fast', .5)

Register a handler to be called when Ajax requests complete


$( document ).ajaxComplete(function( event,request, settings ) {
  $( "#msg" ).append( "
  • Request Complete.
  • " ); });

    Scroll to top

    
    $('html,body').scrollTop(0);
    

    Height and Width

    
    screen.availHeight
    screen.availWidth
    screen.height
    screen.width
    

    Redirect page using jQuery

    
    // similar behavior as an HTTP redirect
    window.location.replace("http://stackoverflow.com");
    
    // similar behavior as clicking on a link
    window.location.href = "http://stackoverflow.com";
    

    Check if an HTML element is empty

    
    if ($('#element').is(':empty')){
      //do something
    }
    

    Load another page or div from another page in DIV

    
    $( "#result" ).load( "ajax/test.html" );
    
    
    $( "#result" ).load( "ajax/test.html", function() {
      alert( "Load was performed." );
    });
    
    
    $( "#result" ).load( "ajax/test.html #container" );
    

    Leave a Reply

    Your email address will not be published.