Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Serialize a form elements in jQuery

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 312
    Comment on it

    The serialize() method of jquery is useful when we have to send a query string to sever in ajax request.
    It can encode all the form elements as a string by serializing the form values.
    This method does not accept any arguments.
    The .serialize() method creates a text string in standard URL-encoded notation.
    It can be applied on a jQuery object that has selected individual controls, such as <form>,<input>, <textarea>, and <select> etc.
    Serialize() method does not accept any arguments.

     

    For example, we have a form that contains dropdown, checkboxes and radio button. After that, we will serialize the form and create a query string that can be used in Ajax call.

    <html>
    <head>
      <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    </head>
    <body>
     
    <form>
      <select name="category" multiple="multiple">
        <option selected="selected">Admin</option>
        <option>User</option>
        <option selected="selected">Tester</option>
      </select>
     
      <br>
      <input type="checkbox" name="role" value="role1" id="role1">
      <label for="ch1">role1</label>
      <input type="checkbox" name="role" value="role2" checked="checked" id="role2">
      <label for="ch2">check2</label>
     
      <br>
      <input type="radio" name="radio" value="yes" checked="checked" id="radio1">
      <label for="r1">Yes</label>
      <input type="radio" name="radio" value="no" id="radio2">
      <label for="r2">No </label>
    </form>
     
     <script>
    
      $( "input[type='checkbox'], input[type='radio']" ).on( "click", showValues );
      $( "select" ).on( "change", showValues );
    
      function showValues() {
          var str = $( "form" ).serialize();
        alert( str );
           $.ajax({
               type: "POST",
               url: "your_url",
               data: $( "form" ).serialize(),
               dataType: "json"
               
          });
       
      }
    </script>
     
    </body>
    </html>

    To check the query string we have added an alert in our function. Whenever we change the value of any control(dropdown,checkbox or radio button), an alert will show the query string.

    In our case it's popping up like string below:

    category=Admin&category=Tester&role=role2&radio=yes

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: