Home > JQuery, Uncategorized > Basic JQuery Tips

Basic JQuery Tips

This is more for my reference and hopefully helps others working with JQuery.

  1. Getting and Setting the innerHTML of an element

    	
    		var content = $("#id").html();
    		$("#id").html("Some HTML");		
       
  2. Getting and Setting the text (with out any HTML) of an element

    		
    		var txt = $("#id").text();			
    		$("#id").text("Some Text");		
    	
  3. Removing content from an element

    		
    		$("#id").empty();		
    	
  4. Getting and Setting style properties

    			
    		var displayValue = $("#id").css("display");
    		
    		$("#id").css("display", "block");
    	
  5. Hiding and Displaying elements

    	
    		// Toggles an element's visibility
    		$("#id").toggle();
    				
    		$("#id").hide();
    		
    		// Sets the display style property to block and not inline
    		$("#id").show();		
    	
  6. Registering to events such as keyup

    		$("#id").keyup(function(){
    			alert($(this).val());
    		});
    	
  7. Dealing with CSS classes

    		// Adds the specified class to the element
    		$("#id").addClass("showme");
    		
    		// Multiple classes should be separated by spaces
    		$("#id").addClass("showme1 showme2");
    				
    		// Removes the specified class
    		$("#id").removeClass("hideme");
    		
    		// Multiple classes should be separated by spaces
    		$("#id").removeClass("hideme1 hideme2");
    		
    		// Removes all the classes
    		$("#id").removeClass();
    	
  8. Getting and Setting values of form elements

    		// For input boxes
    		$("#inputbox").val(); // Returns the text box value
    		$("#inputbox").val("set some value");
    		
    		// For select boxes
    		$("#selectbox").val(); // Returns the selected value 
    		// To get the text of the selected option
    		$("#selectbox :selected").text();
    		
    		// Programatically selects a value or multiple values
    		$("#singleselect").val("123");
    		$("#multipleselect").val(["12", "234"]);
    
    		// For checkboxes and radio buttons
    		$("#chkId").val();  // Returns value whether the check box is checked or not
    		// Returns true when the check box is checked
    		$("#chkId").attr("checked"); 		
    		
    		// Programatically checks the check box
    		$("#chkId").attr("checked", "checked"); 	
    	
Categories: JQuery, Uncategorized Tags:
  1. No comments yet.
  1. July 18th, 2012 at 04:30 | #1