aron
aron

Reputation: 2886

How to check id of textbox in JavaScript?

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")

Upvotes: 1

Views: 387

Answers (2)

Matt
Matt

Reputation: 44068

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

Upvotes: 3

gblazex
gblazex

Reputation: 50109

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);
    }
}

Upvotes: 1

Related Questions