Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically get values of all element inside a div with jQuery

I have a main div and inside of this, there are a lot of input text and radio button.
Like this:

<div id="mainDiv">
   <input type="text" name="text-1" /> <br/>

   <input type="radio" name="radio-1" />Yes
   <input type="radio" name="radio-1" />No <br/>

   <input type="text" name="text-2" /> <br/>
   <input type="text" name="text-3" /> <br/>
</div>
<img src="img/img.gif" onclick="getAllValues();" />

I want to define the function getAllValues() in jQuery to get all values in mainDiv and save them in a string.
It is possible?

like image 808
Danilo Avatar asked Dec 21 '11 10:12

Danilo


2 Answers

To achieve this you can select all the form fields and use map() to create an array from their values, which can be retrieved based on their type. Try this:

function getAllValues() {
    var inputValues = $('#mainDiv :input').map(function() {
        var type = $(this).prop("type");

        // checked radios/checkboxes
        if ((type == "checkbox" || type == "radio") && this.checked) { 
           return $(this).val();
        }
        // all other fields, except buttons
        else if (type != "button" && type != "submit") {
            return $(this).val();
        }
    })
    return inputValues.join(',');
}

The if statement could be joined together here, but I left them separate for clarity.

like image 143
Rory McCrossan Avatar answered Sep 30 '22 19:09

Rory McCrossan


Try something like that:

function getAllValues() {
  var allVal = '';
  $("#mainDiv > input").each(function() {
    allVal += '&' + $(this).attr('name') + '=' + $(this).val();
  });
  alert(allVal);
}
like image 21
dfg Avatar answered Sep 30 '22 17:09

dfg