0

I'm building a javascript to submit an html form automatically using jQuery. I'm wondering if it's possible to create a javascript method that will return a map of all form elements and values if given an identifier to find the form with. I'd rather use such a method than manually specifying jQuery selectors for each form element.

function form_submit(){
    jQuery.ajax({  
        type: 'post',  
        url: '/signup/',  
        data: map_form_elements_values('my_form'),  
        success: function(data, textStatus, jqXHR){
                        //foo
                 }
    });  
    return false; 
}

<form id="my_form" action="">
<input class="" id="name" type="text" name="last-name" />
<select class="" id="fruit" type="select" name="fruit-name" />
<option>bananas</option>
</select>
</form>

the goal would be to have map_form_elements_values('my_form') return a map that can be used by the ajax function. Does anyone know how to do this?

2
  • Take a look at .serializeArray() - api.jquery.com/serializeArray Commented Jun 25, 2011 at 18:41
  • I hope I correctly understood your problem in my answer, but please let me know if not. Commented Jun 25, 2011 at 18:50

3 Answers 3

1

Take a look at the jQuery forms plugin: http://jquery.malsup.com/form/

If you don't need the extra functionality then a simple statement along the lines of:

 myData = $("#formToSubmit").serialize();

        $.ajax({
        type: "POST",
        url: "process_form.php",
        data: myData,
        dataType: "json",
        success: function(data) { ....etc
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! That plugin looks very useful I think I'm going to try using it!
1

I answered on that recently:

JQuery. How to load inputs values to an array?

jQuery.fn.inputs2obj=function (){
        var out={};
        var arr=this.filter(':input').each(function () {
    e=$(this);
        out[e.attr('name')]=e.val();
        }).get();
        return out;
    }

Usage example:

inputs=$('form').find(:input).inputs2obj();

2 Comments

how is this relevant to this question?
jQuery.ajax({ type: 'post', url: '/signup/', data: $('#myform').find(:input).inputs2obj(); success: function(data, textStatus, jqXHR){ //foo } }); return false; }
0

You can use serialize() or serializeArray()

var params = $("#my_form").serialize();
        $.post( "/signup/",params,
                 function(data,textStatus, jqXHR){foo ... } )

See for example

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.