Reputation: 11
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>
Upvotes: 1
Views: 10125
Reputation: 7090
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.
Upvotes: 1