1

I am trying to serializeArray my form submission in jQuery. I am trying to get a JSON like String or Object. Also if someone can let me know how to pick only those widgets which have a value rather than empty ones that would be perfect.

I was in a hurry hence didnt check the syntax and I apologize for it.

   <html>
    <head>
    <script type="text/javascript">

    $(document.ready(function(){
       $("#myform").submit(function(){

           var mySerialObj = $("#myform").serializeArray();

            $.each(mySerialObj,function(indx,idxVal){
                 //here indx is numeric and idxVal is a String like
                 // [{{"name","name"},{"value","RED"}}]

                     $.each(JSON.parse(idxVal),function(i,v){

                           //here I am not able to get the thinggy into a 
                           //  JSON format something like ['name','RED'] 
                        });
});

});


});   


    </script>
    </head>
    <body>

    <form id="myform">
    <div>
    <span>What color do you prefer?</span><br />
    <input type="radio" name="colors" id="red" />Red<br />
    <input type="radio" name="colors" id="blue" />Blue<br />
    <input type="radio" name="colors" id="green" />Green
    </div>

    <div> 
    <select>
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>
    </div>

    </form>

    <button type="submit" value="submit" id="sbmt"">submit</button>


    </body>
    </html>
sv1
  • 11
  • 1
  • 1
  • 2

2 Answers2

1

If you do not care about repetitive form elements with the same name, then you can do:

var data = $("#myform").serializeArray();
var formData = _.object(_.pluck(data, 'name'), _.pluck(data, 'value'));

Using underscore here.

Mitar
  • 6,756
  • 5
  • 54
  • 86
1

Just use:

$("#myform").serialize();

You can try it here.

karim79
  • 339,989
  • 67
  • 413
  • 406
  • Karim: Thanks for your quick response. .serialize will give me like a queryString right? like color=RED&car="VOLVO". So should I objectify this into a JSON object and then loop around with each? And also for the checking of empty vals will :inpu[value] check for all types of widgets like radio buttons, select box etc? or does it only pick textboxes? – sv1 Mar 29 '11 at 02:31
  • @sv1 - Yes, you will get a querystring. I realised that my second example does not pick up the selected option's value. I am editing. – karim79 Mar 29 '11 at 02:33
  • OK..I read it just now in some other question that select boxes also get picked but the "name" attr should be declared in the select – sv1 Mar 29 '11 at 02:38
  • @sv1 - yes, this is true, was wondering why I could get the example working! – karim79 Mar 29 '11 at 02:39
  • 1
    See this question for how to serialize a form to json. http://stackoverflow.com/questions/1184624/serialize-form-to-json-with-jquery – jwwishart Mar 29 '11 at 02:43