JavaScript
Article

jQuery Get/Set Script to Manage Form Values

By Sam Deering

Manage your form values with this awesome jQuery script. It will save you lots of time and help keep you code cleaner and easier to manipulate and reference form values.

Features

  • Get/Set functions for form inputs
  • Integration for all input types including checkbox & radio
  • Clean and easy to use

Usage

//GET
$.field('myInputName');
//returns input value

//SET
$.field('myInputName','myValue');
//sets input value and returns jQuery selector of input

The Code

(function(){
   /**
   * This jQuery Extension adds the ability to access form fields by the shortcut property .field()
   * which gets and sets input field values by name using the .find() method.
   * @param string inputName
   * @param mixed value (optional)
   */
	$.fn.field = function( inputName, value){

		if(typeof inputName!='string' ){
			return false;
		}
	   
		var $inputElement = $(this).find('[name='+inputName+']');
		
		/*
		 *  Get request, return the input fields value.
		 */
		if(typeof value==='undefined' && $inputElement.length>=1)
		{
			switch($inputElement.attr('type')){
				case 'checkbox':
					return $inputElement.is(':checked');
					break;
				case 'radio':
					var result;
					$inputElement.each(function(i,val){
						if($(this).is(':checked'))
							result = $(this).val();
					});
					return result;
					break;
				default:
				   return $inputElement.val();
				   break;
			}
		}
		
		 /*
		 *  Set request, set the input field to the value provided
		 *  and return a reference to the jQuery selector for the input
		 */
		else
		{
			switch($inputElement.attr('type')){
				case 'checkbox':
					$inputElement.attr({checked: value});
					break;
				case 'radio':
					$inputElement.each(function(i){
					   if($(this).val()==value)
					   {
						  $(this).attr({checked: true});
					   }
					});
					break;
				case undefined:
				   $(this).append('' );
				   break;
				default:
				   $inputElement.val(value);
				   break;
			}
			return $inputElement;
		}
	}
})();

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.