0

I was wondering if there is a better way of grabbing data from inputs and then posting them. I have this code here which works fine but I just wanna know if there is something better I can do with it to streamline it.

$('#Subscription').submit(function(e){
    var url = $(this).attr('action'),
        1 = $('input[name=1]').val(),
        2 = $('input[name=2]').val(),
        3 = $('input[name=3]').val(),
        4 = $('input[name=4]').val(),
        5 = $('input[name=5]').val(),
        6 = $('input[name=6]').val(),

    $.post(url, { 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6 }, function (data) {
        // Do something after post
    });

    e.preventDefault();
});
1
  • that code works? Using numbers as variable names? It shouldn't... Commented Sep 25, 2012 at 18:59

2 Answers 2

2

try this http://api.jquery.com/serialize/

Example:

$('#Subscription').submit(function(e){
    var url = $(this).attr('action'),
    var formData= $(this).serialize();

    $.post(url, data:formData, function (data) {
        // Do something after post
    });

    e.preventDefault();
});
Sign up to request clarification or add additional context in comments.

Comments

0

also try out the following code, if you have input elements not inside the form.

<div id="form_clone">
    <input name="name" />
    <input name="id" />
    <input name="contact_details" />
    <input name="info" />
</div>

The 'serialize' function allows only to get the input fields inside a form, but if you want to get the value of input elements inside this element then use:

(function($) {

    $.fn.serializeAnything = function() {

        var toReturn    = [];
        var els         = $(this).find(':input').get();

        $.each(els, function() {
            if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) {
                var val = $(this).val();
                toReturn.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( val ) );
            }
        });

        return toReturn.join("&").replace(/%20/g, "+");

    }

})(jQuery);

Usage:

$('#form_clone').serializeAnything()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.