I have an Element Like
<div class="control">
<label> </label>
<input type="checkbox" id="1"><span class="controlText">Check Box</span>
<div style="display: inline;" class="delete"><sup>x</sup></div>
<div style="display: inline;" class="properties chkbox">Properties</div>
</div>
This element is in a form with id userForm
What I do is when the user clicks on a button it calls a function and searches all the div`s with class control and gets information about the element in that div.
if($("#userForm").children().size() > 1){
var controls = new Array();
$('#userForm').find('div.control').each(function(index, Element)
{
if($(Element).find('input').attr('type') == "checkbox")
{// If element is of type checkbox
var attributes = new Array();
attributes[type] = "checkbox";
attributes[name] = $(Element).find('.controlText').text().toLowerCase().split(" ").join("_")+"_"+$(Element).find('input').attr("id");
attributes[required] = $(Element).find('input').hasClass('required');
controls[index] = attributes;
$.each(attributes, function(key, value) {
// here i need to print the array.
// I need a format of the arrays like
// controls[0]
// =>
// [type] = checkbox
// [name] = chk_name_1
// [required] = ture
// [1]
// => .....
alert( "The key is '" + key + "' and the value is '" + value + "'" );
});
}
});
}
Your code is nearly right, but there are some problems. On the lines where you assign values to the elements of the
attributesarray, you need to put the name of the elements in quotes:Otherwise, it’s looking for a variable called
type, which doesn’t exist.Your
.eachloop will work fine, so you just need to print the values in whatever format you like. Note thatvaluein the loop is an array, so to print thetype, for example, you will need:You are also looping through the wrong collection, so change
$.each(attributes, function(key, value) {to$.each(controls, function(key, value) {