How to get all form elements values using jQuery?
You can use a serialize() function of JQuery:
var datastring = $("#preview_form").serialize();
$.ajax({
type: "POST",
url: "your url.php",
data: datastring,
success: function(data) {
alert('Data send');
}
});
And read in PHP:
echo $_POST['datastring']['dialog_box_textarea_1'];
echo $_POST['datastring']['radiobutton_1'];
........
And get ***data-**** to tag HTML5 you can see this example:
<div id="texto" data-author="Ricardo Miranda" data-date="2012-06-21">
<h4>Lorem ipsum</h4>
<p>
Lorem ipsum dolor sit amet, ius integre eligendi et,
sea ut expetendis conclusionemque,
mel at ornatus invenire. His ad moderatius definiebas omittantur,
liber saepe albucius sea cu.
Audire tamquam dolores vis ne, mediocrem consulatu eum ex.
Duo te agam saepe convenire, et fugit iisque his.
</p>
<script type="text/javascript">
$(function() {
alert("The text is write " + $('#texto').data('author'));
});
And
<div id="texto" data-author='{"nombre":"Ricardo","apellido":"Miranda"}' data-date="2012-06-21">
...
</div>
<script type="text/javascript">
$(function() {
alert("The text is write " + $('#texto').data('author').apellido + ", " +
('#texto').data('author').nombre);
});
</script>
I know you're using jQuery but for those who want a pure Javascript solution:
// Serialize form fields as URI argument/HTTP POST data
function serializeForm(form) {
var kvpairs = [];
for ( var i = 0; i < form.elements.length; i++ ) {
var e = form.elements[i];
if(!e.name || !e.value) continue; // Shortcut, may not be suitable for values = 0 (considered as false)
switch (e.type) {
case 'text':
case 'textarea':
case 'password':
case 'hidden':
kvpairs.push(encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value));
break;
case 'radio':
case 'checkbox':
if (e.checked) kvpairs.push(encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value));
break;
/* To be implemented if needed:
case 'select-one':
... document.forms[x].elements[y].options[0].selected ...
break;
case 'select-multiple':
for (z = 0; z < document.forms[x].elements[y].options.length; z++) {
... document.forms[x].elements[y].options[z].selected ...
} */
break;
}
}
return kvpairs.join("&");
}