Easy jQuery Form Values

December 3, 2009

Been hectic as hell around here, but I still need to make time to post new content. There are always ways to improve and refactor your code, and this should help. You've probably seen some pretty bloated and static ways to grab form values for use in Ajax, and if you're still grabbing each value individually, it's time to step it up.

Edit: Received some valuable criticism from a reader (Mike T.) and altered my post accordingly. Thanks for the comments!

You've seen values retrieved using something similar to:

var name = $('#myForm input[name="userName"]').val();
var website = $('#myForm input[name="website"]').val();
var comment = $('#myForm textarea[name="comment"]').val();

This is almost acceptable if you're only grabbing one or two values, but beyond that it's cumbersome and sloppy. It only gets worse if you're assigning arbitrary id's to each input.

Instead, use the .serialize() function to grab all of your values any time you want to retrieve form information for an Ajax call. This function will take all of your input names and values and format them for the server. Keep in mind for elements such as radios and checkboxes that serialize will grab only the :selected and or :checked items.

The HTML

<!DOCTYPE html>
<html>
<head>
	<title>Grabbing Form Values</title>
</head>
<body>

<form id="myForm">
    <input type="text" name="firstName" />
    <br />
    <input type="text" name="lastName" />
    <br />
    <input type="radio" name="receiveEmail" value="yes" />  
    <input type="radio" name="receiveEmail" value="no" />
    <br />
    <textarea name="comments"></textarea>
    <br />
    <input type="submit" value="Submit" />
</form>

</body>
</html>

Now we can use the function to retrieve our form info and send it off.

The Usage

function sendForm(){ // Your Ajax function for sending info
  var formInfo = $('#myForm').serialize(); // Grab form values
  $.post('_myPHP.php', // Use .post() for your Ajax call
        formInfo,
        function(data){
          // Do something on successful return
        }
  ); 
}

Obviously there is a lot more you can do here such as validating your info or attaching the function directly to a .submit() call, but this should get the ball rolling in the right direction.

Love it? Hate it? Leave a comment.





Close
* * *