Examples

Text Inputs

Basic form validation.

<form id="form">
	<input type="text" name="name" value="Joe Bloggs" />
	<input type="text" name="email" value="test@test.com" />
	<textarea nmae="message">Hi There!</textarea>
	<button>Submit</button>
</form>

<script>

    $('#form').on('submit', function(){
		
	//Gather form data
        var data = $(this).serializeObject();

        //Return value(s)
        //data.name = "Joe Bloggs"
        //data.email = "test@test.com"
        //data.message = "Hi There!"
		
	//Test required fields are not empty.
	if(!data.name || !data.email || !data.message){
		alert('Please Ensure All Fields Are Filled Out!');
		return false;
	}
	
	//Test a valid email address has been submitted
	if(data.email){
		alert('Please Provide A Valid Email Address!');
		return false;
	}

	return true;

    }); 

</script>

Multiselect and Checkbox Inputs

Inputs that can handle more than one value, will store the values as an object. If only one choice is made, the value will be stored as a string.

<form id="form">
	<label for="">Select Post Types To Include</label>
	<select name="post_type" multiple>
		<option value="posts" selected>Posts</option>
		<option value="pages">Pages</option>
		<option value="products" selected>Products</option>
	</select>
        <button>Submit</button>
</form>

<script>

    $('#form').on('submit', function(){

       	//Gather form data
        var data = $(this).serializeObject();

        //Return value(s)
        //data.post_type = {post : true, products : true}

        if( data.post_type.posts || data.post_type.pages || data.post_type.products ){
		alert('Save Options Updated!');
		return true;
        }

        return false;

    });

</script>

Array Inputs (Linear & Associative)

To create an array input, append ‘[]’ to the end of the inputs name attribute. This will return an array of values. To create an associative array add a property name into the square brackets(‘[property_name]’) and an object of key/values will be returned instead.

<form id="form">
	<label>Name</label>
	<input type="text" name="name[first_name]" value="Joe" />
	<input type="text" name="name[last_name]" value="Bloggs" />
	<br />
	<label>Phone Number(s)</label>
	<input type="text" name="email[]" value="test@test.com" />
	<input type="text" name="email[]" value="test@test.co.uk" />
	<button>Submit</button>
</form>

<script>

    $('#form').on('submit', function(){

        var data = $(this).serializeObject();
		
	//Return Value(s)
	//data.name = {first_name : "Joe", last_name : "Bloggs"}
        //data.email = ["test@test.com", "test@test.co.uk"]

        if(data.name.first_name && data.name.last_name){
        	name = data.name.first_name+" "+data.name.last_name+", ";
        }

	for(i=0;i<data.email.length;i++){
		if(data.email[i]){
			alert(name+'Please Provide A Valid Email Address!');
			return false;
		}
	}

	return true;

    });

</script>