views:

44

answers:

2

Hello, I have this great javascript that automatically populates the values of all textboxes on a page with a number, starting at 1 then increasing.

 function editTextBoxes() {
        var textboxs = $('input:text');

        for (i = 0; i <= textboxs.length; i++) {
            $('input:text:eq(' + i + ')').val(i + 1);
        }
    }

However, I only want to fill textboxes who's id contain txtSortOrder

Can someone please help me fix this line: (it's just a guess)

if ($('input:text:eq(' + i + ')').ID.Contains("txtSortOrder")
+3  A: 

You can pull any attribute using the attr function. For the Contains(), you can use indexOf which will return -1 if the search is not found.

So that brings us this far:

if ($('input:text:eq(' + i + ')').attr('id').indexOf("txtSortOrder") !== -1)

Now, for your iteration, you can actually use each to process the results of your query.

E.g.

function editTextBoxes() {
    $('input:text[id~=txtSortOrder]').each(function (index) {
        $(this).val(index + 1);
    });
}

Notice this extends your selector to use Attribute Contains word Selector: input:text[id~=txtSortOrder]

Which means you do not have to do the ID comparison manually

Matt
+1 It worked, thanks!
aron
Ah, no it's not equals txtSortOrder, but just contains it.
aron
@aron - oops, you're right. :) It would be `~=` rather than `!=` - see my update.
Matt
+1  A: 

Code:

function editTextBoxes() {
    // it will select all textboxes which id contain txtSortOrder
    var textboxs = $('input:text').filter(function(){
        this.id.indexOf("txtSortOrder") !== -1;
    });

    for (i = 0; i <= textboxs.length; i++) {
        $('input:text:eq(' + i + ')').val(i + 1);
    }
}
galambalazs
+1 like this solution because it has the filter. With the filter it keeps the order in sync. However I think there might be a small issue with the code because it did not work for me.
aron