Margret Kristjansdottir Margret Kristjansdottir - 4 months ago 8
jQuery Question

jQuery .each() and CodeMirror

I'm creating CodeMirror textareas in many different tabs and I need to loop through the textareas in the tab that's being created on a click. I have found the elements, that's the textareas that I need to convert. I'm trying to use jQuery

.each()
to go through them and convert to CodeMirror:

var queryBuilder = $(tabPanelDiv).find(".QueryBuilder");
queryBuilder.each(function(index, el) {
var editorQuery = CodeMirror.fromTextArea($(el)[index], {
lineNumbers: true,
tabMode: "indent",
mode: "text/x-sql",
theme: "eclipse"
});
queryArr.push(editorQuery);
});


The problem that I'm having is my lack of experience with
.each()
and how to insert the element into
CodeMirror.fromTextArea()
. In this
.each()
the conversion works for the first textarea but the second one always goes to CodeMirror code as undefined. I have all the 5 textareas but I'm using the
index, el
parameters the wrong way. Can anyone help me with this?

Answer

Ignore index. Inside each, the el argument is the correct element at that index, the index argument is simply so you can be aware of where you are in the set you're iterating over.

You should be simply using el, not $(el)[index]:

queryBuilder.each(function(index, el) {            
    var editorQuery = CodeMirror.fromTextArea(el, {
      ...
    });
    queryArr.push(editorQuery);
});

Also, because you're turning one array (of elements) into another array (of CodeMirror objects) you should be using map, not each:

var queryArr = queryBuilder.map(function(index, el) {            
    return CodeMirror.fromTextArea(el, {
      ...
    });
});
Comments