开发者

How to check id of textbox in JavaScript?

开发者 https://www.devze.com 2023-01-05 16:14 出处:网络
I have this great JavaScript that automatically populates the values of all textboxes on a page with a number, star开发者_Python百科ting at 1 then increasing.

I have this great JavaScript that automatically populates the values of all textboxes on a page with a number, star开发者_Python百科ting 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")


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


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

精彩评论

暂无评论...
验证码 换一张
取 消