apply javascript eventlistener on multiple textboxes whose id starts with

I'm working with JavaScript eventlistener

Right now I have this:

            // ----- Event Listener - TextBox Click -----
            document.getElementById('DataGridA_txtBox1').addEventListener('click', function () {

                // get value of textbox and save in variable
                var x = document.getElementById("DataGridA_txtBox1").value;

                // after clicking in textbox save existing textbox value in hiddenfield1
                document.getElementById('HiddenField1').value = x;

            })
            // ----- Event Listener - TextBox Click -----


The above event listener works fine.
When I click in a Textbox called DataGridA_txtBox1, then the value of the textbox is stored in HiddenField1


What if I have 3 textbox on my page.

The texboxes on my page would be called this:

DataGridA_txtBox1
DataGridA_txtBox2
DataGridA_txtBox3

I only want to have one event listener.

Is there a way so revise my click event so that the click event applies to any textbox whose id starts with DataGridA_txtBox?
LVL 1
maqskywalkerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Zakaria AcharkiAnalyst DeveloperCommented:
Yes that is possible and could be achieved like :

var inputs = document.querySelectorAll("input[id^=DataGridA_txtBox]");

var myFunction = function() {
    alert( this.value );
};

for (var i = 0; i < inputs.length; i++) {
    inputs[i].addEventListener('click', myFunction, false);
}

Open in new window


For the hidden input fields, we need to know how you will use them you will have hidden field for every text input, could you share with use the HTML structure you're going to use, that will help us to adjust the script with your structure.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
maqskywalkerAuthor Commented:
Nice solution!
Zakaria AcharkiAnalyst DeveloperCommented:
Glad I could help.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.