开发者

Associative arrays in Jquery with Traversing Each Element

开发者 https://www.devze.com 2023-03-20 17:26 出处:网络
I have an Element Like <div class=\"control\"> <label>&nbsp;</label> <input type=\"checkbox\" id=\"1\"><span class=\"controlText\">Check Box</span>

I have an Element Like

<div class="control">
      <label>&nbsp;</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开发者_如何学C 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 attributes array, you need to put the name of the elements in quotes:

attributes["type"] = "checkbox";

Otherwise, it's looking for a variable called type, which doesn't exist.

Your .each loop will work fine, so you just need to print the values in whatever format you like. Note that value in the loop is an array, so to print the type, for example, you will need:

value["type"]

You are also looping through the wrong collection, so change $.each(attributes, function(key, value) { to $.each(controls, function(key, value) {

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号