Basic JQuery Tips
This is more for my reference and hopefully helps others working with JQuery.
-
Getting and Setting the innerHTML of an element
var content = $("#id").html(); $("#id").html("Some HTML");
-
Getting and Setting the text (with out any HTML) of an element
var txt = $("#id").text(); $("#id").text("Some Text");
-
Removing content from an element
$("#id").empty();
-
Getting and Setting style properties
var displayValue = $("#id").css("display"); $("#id").css("display", "block");
-
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();
-
Registering to events such as keyup
$("#id").keyup(function(){ alert($(this).val()); });
-
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();
-
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");