0

I've this HTML table:

<table class="table table-condensed">
    <thead>
        <tr>
            <th><input type="checkbox" id="toggleCheckboxSelFabricante" name="toggleCheckboxSelFabricante"></th>
            <th>Fabricante</th>
        </tr>
    </thead>
    <tbody id="selFabricanteBody">
        <tr>
            <td><input type="checkbox" name="selChkFabricante" id="selChkFabricante3" value="3"></td>
            <td>Eos est ipsam.</td>
        </tr>
    </tbody>
</table>

I need to create a key => value for manufacturerColl var where id is the value of each checked checkbox (first td on the table) and name is the text on the second column but don't know how to. This is what I've in my code:

var checkedModelBranch = $("#parMarcaModeloFabricanteBody").find("input[type='checkbox']:checked"),
                checkedManufacturers = $("#selFabricanteBody").find("input[type='checkbox']:checked"),
                manufacturerColl = [],
                modelBranchManufacturerCollection;


        for (var j = 0; j < checkedManufacturers.length; j++) {
            manufacturerColl.push(checkedManufacturers[j].value);
        }

        for (var i = 0; i < checkedModelBranch.length; i++) {
            modelBranchManufacturerCollection = addNewRelationModelBranchManufacturer(checkedModelBranch[i].value, manufacturerColl);
            if (modelBranchManufacturerCollection) {
                for (var k = 0; k < modelBranchManufacturerCollection.manufacturerKeyCollection.length; k++) {
                    $("#parMarcaModeloFabricanteBody td#" + checkedModelBranch[i].value).html(modelBranchManufacturerCollection.manufacturerKeyCollection[k] + '<br/>');
                }
            }
        }

What I need in others words is for each manufacturerColl have and id => name, ex:

manufacturerColl[] = {
  id: someId,
  name: someName
};

And I'm not sure but maybe this could work:

   // move foreach selected checkbox and get the needed
   for (var j = 0; j < checkedManufacturers.length; j++) {
        manufacturerColl.push({
            id: checkedManufacturers[j].value,
            name: "" // how do I get the value on the second column?
        });
    }

Which is the right way to do this? How do I get the value on the second column on each iteration?

Approach

I don't know if this is complete right but is what I've done and it's buggy. See the code:

var checkedModelBranch = $("#parMarcaModeloFabricanteBody").find("input[type='checkbox']:checked"),
                checkedManufacturers = $("#selFabricanteBody").find("input[type='checkbox']:checked"),
                // I added this var to get all the names 
                checkedManufacturersName = $("#selFabricanteBody").find("input[type='checkbox']:checked").parent().next('td').text(),
                manufacturerColl = [],
                modelBranchManufacturerCollection;


        for (var j = 0; j < checkedManufacturers.length; j++) {
            manufacturerColl.push({
                id: checkedManufacturers[j].value,
                // Here I'm tying to put the entire name but get only the first character
                name: checkedManufacturersName[j]
            });
        }

        for (var i = 0; i < checkedModelBranch.length; i++) {
            modelBranchManufacturerCollection = addNewRelationModelBranchManufacturer(checkedModelBranch[i].value, manufacturerColl);
            if (modelBranchManufacturerCollection) {
                //$("#parMarcaModeloFabricanteBody td#" + checkedModelBranch[i].value).siblings().attr("rowspan", modelBranchManufacturerCollection.manufacturerKeyCollection.length);

                for (var k = 0; k < modelBranchManufacturerCollection.manufacturerKeyCollection.length; k++) {
                    // then I render the name attribute from the collection
                    $("#parMarcaModeloFabricanteBody td#" + checkedModelBranch[i].value).append((modelBranchManufacturerCollection.manufacturerKeyCollection)[k].name + '<br/>');
                }
            }
        }

Why I'm inserting/getting the first character only and not the complete string?

3
  • @apsillers I added some extra info to the main post, take a look and see if that clear a bit the question and what I need Commented Oct 30, 2014 at 20:46
  • If you mean the text next to the checkbox in the HTML, its just text. There's no way to get it easily. You could wrap it in a span with an id or have a map hardcoded like so ['text1', 'text2'] where the array indices are the checkbox values (sparse arrays are one of the few things javascript handles well) and when you iterate through the checked checkboxes just pull the 'name' values from that array. Commented Oct 30, 2014 at 20:50
  • @JaredSmith and by doing as you suggested how do I get then? Commented Oct 30, 2014 at 20:51

2 Answers 2

1

//Since your input and text are wrapped in td elements

In the code:

var checked = $('#selFabricanteBody').find('input[type="checkbox"]:checked');
var arr = [], j = checked.length, item;

while(j--) {
    item = list[j];
    //gets the text from the next child, assumes its the text
    //if the text is before checkbox, use previousSibling
    arr.push({id: item.value, name: item.parentNode.nextSibling.nodeValue});
}
Sign up to request clarification or add additional context in comments.

7 Comments

Sorry I made a typo on the main post and for that the table where all is wrapped was not showed
Before goes through this one, can you take a look to my latest edit?
I have a hard time believing method chaining will work here. You should really use a loop like in my answer. Use $().find() to get the initial list if you want but iterate through it and get node.nextSibling.nodeValue to push into the checkedManufacturerName array.
The checkboxes comes from here checkedManufacturers = $("#selFabricanteBody").find("input[type='checkbox']:checked") how do I fit this on your code and a bit lost
You're fine. Updated my answer
|
0

This is what I use to create an object, for sending to a controller method that is looking for a class/model as a parameter:

function ExtractModel(array) {
var modelString = '';
var model = {};
//var array = arrayString.split('&');
var isObjectModel = $.isPlainObject(array);
if (!isObjectModel) {
    $(array).each(function (index, element) {
        var typeId = element.split('=')[0];
        var val = element.split('=')[1];
        if (element == null) { } else {
            model[typeId] = (val);
        }
    });
} else {
    model = array;
}
return model;

};

So, with this, I am taking a url parameter string and creating an object from it; the parameter string is generated from serializing the form. The "model" automatically creates the property that is represented by "typeId"; if "typeId" = "hello", then a new property or object item will be created, named "hello" (model.hello will get you a value). You can use this same logic to loop through the elements on your page to populate the object with multiples. Make sure to set your variable "modelBranchManufacturerCollection" equal to {}, and to then set the index of where to insert a new one.

This should do what you want:

 var ids = [1, 2, 3, 4, 5, 6]
var names = ['a', 'b', 'c', 'd', 'e', 'f']

var mainObj = {};

$(ids).each(function (index, element) {
    var miniObj = {};
    miniObj['id'] = ids[index];
    miniObj['name'] = names[index];
    mainObj[index] = miniObj;
});

returns 6 items of id and name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.