Using jQuery with forms - part 4 (Attributes)

Wednesday, 2 December 2009


This is the fourth in a series of tutorials on using jQuery to manipulate forms. In this series I will be looking at parts of the jQuery API reference in detail. In this tutorial I will be looking at forms and jQuery Attributes.

Attr


attr(name)

Retrieves the value of an attribute


// Retrieve the location that the form is submitting to
$("#my_form").attr("action"); 

attr(key, value)

Sets the value of an attribute


// Set the location that the form is submitting to, this may be 
useful when you want to set the action according to some input
$("#my_form").attr("action", "processing.php"); 

removeAttr(name)

Removes an attribute from an element


// Remove all inline styling from fields with the password class
$(".password").removeAttr("style"); 


HTML


html() / html(val)

Retrieves / sets the innerHTML of the matched element


// Retrieve the html() contents of the fieldset with ID 
#fieldset_login and then set the html to the 
contents of updatedHTML
var updatedHTML = ... some markup ...
var login_html = $("#fieldset_login").html(updatedHTML);


Text


text() / text(val)

Retrieves / sets the text contents of the matched element


// Retrieve the contents of the first label
var label_text = $("label:first").text();


Getting and setting the values of different form elements



// Retrieve and set the contents of text input
$("#my_text_input").val();
$("#my_text_input").val(new_value);

// Retrieve and set the contents of label
$("#my_label").text();
$("#my_label").text(new_value);

// Retrieve and set the contents of textarea
$("#my_textarea").val();
$("#my_textarea").val(new_value);

// Retrieve and set the value of select
$("#my_select").val()
$("#my_select").val(2) // Set select according to value

// Retrieve and set the text of select
$("#my_select :selected").text() // Text value of selected option
// Changes the text of selected option
$("#my_select :selected").text("some text") 

// Retrieve and set the text label of a button
$("#my_button").text();
$("#my_button").text("some text");

// Retrieve the button type attribute
$("#my_button").attr("type"); 

// Retrieve the value of the checked radio element
$("#my_form [name='radio_group']:checked").val();

// Check if a particular checkbox has been checked
$("#my_form [name='checkbox_group[]']").eq(1).is(":checked")

// Retrieve all the checked checkboxes in a serialized string
$("#my_form [name='checkbox_group[]']:checked").serialize() 

// Retrieve and set the contents of password input
$("#my_text_input").val();
$("#my_text_input").val(new_value);


If you found this post useful, here are part 1, part 2, and part 3 of this series.
blog comments powered by Disqus