55

Here is the HTML code:

<!DOCTYPE html><html xmlns='http://www.w3.org/1999/xhtml' >
<head>
    <title>HTML Form Builder</title>
    <link href='css/font1.css' rel='stylesheet' type='text/css'>
    <link href='css/font2.css' rel='stylesheet' type='text/css'>
    <link rel='stylesheet' href='css/style.min.css' type='text/css' media='all' />
    <link rel='stylesheet' href='css/form.min.css' type='text/css' media='all' />
    <link rel='stylesheet' href='css/style1.css' type='text/css' media='all' id='css-theme'/>
    <link type='text/css' href='css/redmond/jquery-ui-1.8.23.custom.css' rel='stylesheet' />
    <link rel='stylesheet' href='css/tipsy.css' type='text/css' media='all' />
    <script type='text/javascript' src='js/jquery-1.8.0.min.js'></script>
    <script type='text/javascript' src='js/jquery-ui-1.8.23.custom.min.js'></script>
    <script type='text/javascript' src='js/jquery.metadata.js'></script>
    <script type='text/javascript' src='js/jquery.validate.js'></script>
    <script type='text/javascript' src='js/jquery.tipsy.js'></script>
    <script type='text/javascript' src='js/jquery.json-2.3.min.js'></script>

    <script type='text/javascript' src='js/main.min.js'></script>
    <script type='text/javascript'>
    $(function(){
        changeInnerHTML('doctor_id');
        changeInnerHTML('hospital_id');
        changeInnerHTML('clinic_id');
        changeInnerHTML('stockist_id');
        changeInnerHTML('chemist_id');
        changeInnerHTML('bloodbank_id');
        changeInnerHTML('dialysis_id');
        
    });
    function changeInnerHTML(id)
    {
        if($('#dialog_box_'+id).length)
        {
            var tmp=id.split('_');
             $.get('getDataValues.php?ref='+tmp[0],function(data,status){
                $('#dialog_box_'+id).html(data);
            });
        }
    }
    </script>
    </head>
    <body>
    <div id='container'>
    

        <h1 id="form-name" style="background-color: rgb(255, 255, 255); box-shadow: none; border: none; margin: 8px 15px;">New Form</h1>
        <form method="POST" id="preview_form" novalidate="novalidate">
            
            
        <div class="row" style="display: block;"><label class="field" for="textarea_1">textarea_1</label><span class="textArea" data=""><textarea id="dialog_box_textarea_1" name="textarea_1" data="{&quot;validate&quot;:{&quot;required&quot;:false,&quot;messages&quot;:{}}}"></textarea></span></div><div class="row" style="display: block;"><label class="field" for="radiobutton_1">radiobutton_1</label><span class="radioButton" data="" id="radiobutton_1"><label class="option" for="radiobutton_1_option_1"><input class="radio" id="dialog_box_radiobutton_1_option_1" type="radio" name="radiobutton_1" value="Option 1" data="{&quot;validate&quot;:{&quot;required&quot;:false,&quot;messages&quot;:{}}}">Option 1</label><label class="option" for="radiobutton_1_option_2"><input class="radio" id="radiobutton_1_option_2" type="radio" name="radiobutton_1" value="Option 2">Option 2</label><label class="option" for="radiobutton_1_option_3"><input class="radio" id="radiobutton_1_option_3" type="radio" name="radiobutton_1" value="Option 3">Option 3</label></span></div><div class="row" style="display: block;"><label class="field" for="checkboxgroup_1">checkboxgroup_1</label><span class="checkBoxGroup" data="" id="checkboxgroup_1"><label class="option" for="checkboxgroup_1_option_1"><input type="checkbox" class="checkbox" name="checkboxgroup_1[]" id="dialog_box_checkboxgroup_1_option_1" value="Option 1" data="{&quot;validate&quot;:{&quot;required&quot;:false,&quot;messages&quot;:{}}}">Option 1</label><label class="option" for="checkboxgroup_1_option_2"><input type="checkbox" class="checkbox" name="checkboxgroup_1[]" id="checkboxgroup_1_option_2" value="Option 2">Option 2</label><label class="option" for="checkboxgroup_1_option_3"><input type="checkbox" class="checkbox" name="checkboxgroup_1[]" id="checkboxgroup_1_option_3" value="Option 3">Option 3</label></span></div><div class="row" style="display: block;"><label class="field" for="dropdown_1">dropdown_1</label><span class="dropDown" data=""><select id="dialog_box_dropdown_1" name="dropdown_1" data="{&quot;validate&quot;:{&quot;required&quot;:false,&quot;messages&quot;:{}}}"><option value="Option 1">Option 1</option><option value="Option 2">Option 2</option><option value="Option 3">Option 3</option></select></span></div><input type="button" class="button blue" value="Submit" id="submit-form"><input type='hidden' id='tname' name='tname' value='surveyForm_2' /></form></div> <!--container-->

<script type='text/javascript' src='js/form.min.js'></script>
</body>
</html>

Here the code which will get all form field values:

 $("#hidAll").append($("#preview_form :input").map(function () {
     if ($(this).val() != 'Submit') {
         if ($(this).is('select')) {
             var aa = $(this).children('option').map(function () {
                 return $(this).val();
             }).get().join("|");
             return $(this).attr('name') + '|' + aa;
         } else if ($(this).is('input:checkbox')) {
             return $(this).attr('name').substring(0, $(this).attr('name').length - 2) + '|' + $(this).val();
         } else {
             return $(this).attr('name') + '|' + $(this).val();
         }
     }
 }).get().join(","));
 alert($("#hidAll").html());

From this I am getting the output value as follows:

textfield_1|dgdfg,
checkboxgroup_1|Option 1,
checkboxgroup_1|Option 2,
checkboxgroup_1|Option 3,
radiobutton_1|Option 1,
radiobutton_1|Option 2,
radiobutton_1|Option 3,
dropdown_1|Option 1!Option 2!Option 3

I want the out as following:

textfield_1|dgdfg,
checkboxgroup_1|Option 1!Option 2!Option 3,
radiobutton_1|Option 1!Option 2!Option 3,
dropdown_1|Option 1!Option 2!Option 3
2
  • 9
    Before writing a form-serializer yourself, did you have a look at: .serialize?
    – Yoshi
    Feb 18, 2013 at 12:40
  • 5
    What are you doing with the output? If you're sending this with AJAX, there are easier ways.
    – Ja͢ck
    May 3, 2013 at 6:52

9 Answers 9

147
+50

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>
4
  • 11
    Wow.... I never knew about .serialize() until just now... I've been gathering inputs by their IDs over and over.... ommyyygeerrrddd
    – RCNeil
    May 6, 2013 at 20:28
  • Awesome! The only thing is I think it would be echo $_POST['dialog_box_textarea_1']; without datastring Mar 22, 2019 at 17:20
  • 1
    You've saved my day, one interesting thing is that you can select which form fields to serialize just not defining "name" in that tag, serialize function only takes elements with name defined. For example I have a date picker and a hidden field where I put the formatted date, just removing the name from the date picker and defining name in the hidden field, serialize only gathers the hidden field not the datepicker.
    – lisandro
    Oct 18, 2019 at 18:08
  • Isn't this serializing the form to POST format? I want to send it as JSON which I don't thing there is a serializer for it
    – AaA
    Sep 6, 2021 at 7:40
15

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("&");
}
8

jQuery has very helpful function called serialize.

Demo: http://jsfiddle.net/55xnJ/2/

//Just type:
$("#preview_form").serialize();

//to get result:
single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1
5

Try this for getting form input text value to JavaScript object...

var fieldPair = {};
$("#form :input").each(function() {
    if($(this).attr("name").length > 0) {
        fieldPair[$(this).attr("name")] = $(this).val();
    }
});

console.log(fieldPair);
1
  • Cache $( this ) in a variable so you're not creating a new jQuery object with every $( this ) call. i.e. var $this = $( this ); ... $this.attr( 'name' ) ... $this.val().
    – hungerstar
    Aug 15, 2018 at 14:32
3

Add this on to the end of it:

var array = $("#hidAll").html();

x = array.split(',');
key=s="";
for (i=0; i<x.length; i++) {
  oldkey = key;
  key = x[i].split('|')[0];
  if (oldkey==key) s+='!';
  else s+=',\n'+key+'|';
  s+=x[i].split('|')[1];
}
s = s.substring(1);
$('#hidAll').html(a);
2

I needed to get the form data as some sort of object. I used this:

$('#preview_form').serializeArray().reduce((function(acc, val) {
  acc[val.name.replace('[', '_').replace(']', '')] = val.value;
  return acc;
}), {});
2
  • Uncaught TypeError: $(...).serialize(...).reduce is not a function. What am I missing?
    – dearsina
    Feb 12, 2021 at 11:01
  • 1
    @dearsina i's been a while, but I would check that the form is an object (name="contact[name]", (name="contact[email]") Feb 14, 2021 at 7:12
1

The answer already been accepted, I just write a short technique for the same purpose.

var fieldPair = '';
$(":input").each(function(){
fieldPair += $(this).attr("name") + ':' + $(this).val() + ';';
});

console.log(fieldPair);
1

If you want to use $(formName).serializeArray() or $(formName).serialize(), you must add name='inputName' on your input element. or will not work!

-1

if you want get all values from form in simple array you may be do something like this.

function getValues(form) {
    var listvalues = new Array();
    var datastring = $("#" + form).serializeArray();
    var data = "{";
    for (var x = 0; x < datastring.length; x++) {
        if (data == "{") {
            data += "\"" + datastring[x].name + "\": \"" + datastring[x].value + "\"";
        }
        else {
            data += ",\"" + datastring[x].name + "\": \"" + datastring[x].value + "\"";
        }
    }
    data += "}";
    data = JSON.parse(data);
    listvalues.push(data);
    return listvalues;
};
2
  • Josue -- I'm not sure why this is getting downvoted, (You are a first time user and we should be encouraging positive answers), but maybe because the accepted answer is better (i.e. this does not add anything to the discussion), or maybe there is not enough information about why your proposal works better than the original code or other answers.
    – Jay Elston
    Dec 29, 2015 at 23:13
  • The method what I posted, returns values in a similar way, except that replaces the symbol | by the of : Jan 4, 2016 at 17:03

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.