apply javascript eventlistener on multiple textboxes whose id starts with

maqskywalker
maqskywalker used Ask the Experts™
on
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?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Analyst Developer
Distinguished Expert 2018
Commented:
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.

Author

Commented:
Nice solution!
Zakaria AcharkiAnalyst Developer
Distinguished Expert 2018

Commented:
Glad I could help.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial