1

I would like to know if it is possible to loop through all the textboxes on a page and insert a value into each one starting with the number 1 and going up by +1. There are over 150 textboxes on this page and they are not in an array and I would not like to rename them one by one.. :-(

Thanks for any help....

1
  • "rename" or "set a value", what should it be? Commented May 27, 2011 at 21:49

3 Answers 3

5
var input = document.getElementsByTagName("INPUT");
var j = 0;

for (var i = 0; i < input.length; i++) {
  if (input[i].type == "text") {
    input[i].value = ++j;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@matt Yes, it seems. It isn't. ;)
1
function FillTextBoxes()
{
    var tbs = document.getElementsByTagName("input");
    var valCount = 0;

    for (var i = 0 ; i < tbs.length ; i++)
    {
        if (tbs[i].type == "text")
        {
            tbs[i].value = ++valCount;
        }
    }
}

window.onload = FillTextBoxes;

2 Comments

There was a bug in it. Updated after reading Tomalak's answer.
ok, but this one works also.. :-) thanks so much guys for all of ur help
1

Try this out:

$('input[type="text"]').each(function(index) {

    $(this).val(index);

})

Per the request of some, for completeness' sake, the above requires the JavaScript library, jQuery. You can reference it like so:

<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.js"></script>

If you aren't using <!DOCTYPE html> you can include the type="text/javascript" attribute.

5 Comments

That does work but the OP didn't mention they are using jQuery
@Matt - True, but you never know. =)
It needs jquery, and he doesn't seem to mention it
@Chuck - Yes ... I know that, and Matt already commented on that before you. He didn't NOT mention it either. =D It's always nice to see all possibilities from the standpoint of the asker, wouldn't you agree?
Add <script type='text/javascript' src='code.jquery.com/jquery-1.6.js'></script> for completeness.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.