Many times we face the problem of getting all the form controls or elements values of a long form. Because sometime getting so many controls by their id or name is very typical that make a long list. So we need to opt a short way for getting all element values using jQuery. We are describing the following ways here.
Getting all element values using jQuery
1. Iterating through all of the elements in a selector and store them into an array :
1 2 3 4 5 6 7 8 9 | <script type="text/javascript" language="javascript"> $(document).ready(function () { ctrl = $('#selectorId'); var selectVal = new Array(); $('input[type=text], textarea,select', ctrl).each(function(){ selectVal.push($(this).val()); }); }); </script> |
Here we are using selector in which elements are and need to loop through all type of elements and store their values in an array. If want we can add their values in a string also. If we want to implement any type of logic to get filtered values then also place the code inside this $.each
.
2. Iterating through all of the elements in a selector and store them into an object:
Generally we store key-value pair in an object as follows:
1 2 3 4 5 6 7 8 | $(document).ready(function () { var selectVal = new Object(); data.fname = $('#fname').val(); data.lname = $('#lname').val(); data.email = $('#email').val(); data.username = $('#username').val(); data.pwd = $('#pwd').val(); }); |
But If there are more elements then it’s typical to list out each and every element one by one. So here we are explaining the short and easy way to achieve this.
1 2 3 4 5 6 7 8 9 10 | $(document).ready(function () { ctrl = $('#selectorId'); var selectVal = new Object(); $('input[type=text], textarea, select',ctrl).each(function(){ var key = $(this).attr('id') selectVal[key] = $(this).val(); }); }); |
Here we are using some of element types to iterate in the given selector and getting their id attribute as key in the object and assign the value in that key. If we are passing this object to server side then we can use this key to get the value.
3. Using serialization (serialize()/serializeArray()) :
If we are using form then we can use serialize method for getting the element values using jQuery as follows:
1 | $('#myForm').serialize() |
Outputs (for example) this url encoded string.
1 | myElemA=my+input+a&myElemB=my+input+b&myElemC=my+input+c |
1 | $('#myForm').serializeArray() |
is similar, but instead of a string, you get an object, with the form element names as keys corresponding to the current values. It would look like this:
1 | {"myElemA":"my input a", "myElemB":"my input b", "myElemC":"my input c"} |
If you are facing any type of problem to implement this post or getting all element values using jQuery, you can write us immediately.