0

Sorry for the horrible title, but basically what I am doing is, I have a template that generates a backbone view when the plus button is pressed. It's a pretty simple form that has some text inputs, and select drop downs. I want to validate the form by highlighting the areas that are duplicates. In my underscore template currently, I have

<div id="#index1-<%=dataId%>">

So my model that has a dataId property makes the id unique. Then I can select by attribute to highlight that div in red. While I was searching on how to select ids that start with something, I came across this post: jquery how to select all the class elements start with "text-"?

The author talks about how to use class instead. What I'm doing when I validate is adding a class of style error in order to highlight things in red and stuff. So iterating through all my child views on the page that were added with the plus button looks like:

       var lastIndex1;
       _.each(this.childViews, function (childView) {
            var dataId = childView.model.get('dataId');

            var index1 = childView.$('#index1-' + dataId).val();
            if (lastIndex1 == index1) {
                $('#index1-' + dataId).addClass('error');
            } else {
                lastIndex1 = index1;
                $('#index1-' + dataId).removeClass('error');
            }
        });

So basically, I end up iterating through my views, and if that current view has a problem, I add my error class. I was wondering if this implementation could improved by using some sort of class in the html so I don't have to use dataId at all.

Originally when I first wrote the code, if I don't add the dataId at the end, then it only highlights one of the ids that are incorrect (since multiple items have the same id). Can classes work for this situation? Thanks in advance!

Community
  • 1
  • 1
Crystal
  • 28,460
  • 62
  • 219
  • 393

1 Answers1

0

if you are assigning a unique id to each element then it should work just the same as using a class name. Your issue may be with your first line in the childView function,. your dataId var may be getting the same value each time, and not the current item you are iterating over. Im not familiar with undescore, but you might try something like var dataId = this.model.get('dataId');

lukeocom
  • 3,243
  • 3
  • 18
  • 30