Skip to main content

jQuery Get/Set Script to Manage Form Values

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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;
		}
	}
})();

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn valuable skills with a practical introduction to Python programming!


Give yourself more options and write higher quality CSS with CSS Optimization Basics.