JavaScript selector

maqskywalker
maqskywalker used Ask the Experts™
on
On button click event how do I assign a variable value to textbox whose Id starts with txtemployee
If

I want to do it with JavaScript, not jQuery.

See I have 3 texboxes.

They are called:

txtemployee1
txtemployee2
txtemployee3

Normally I do this with jquery selector. But I'm trying to learn to do the same only using JavaScript.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Try this:
https://jsfiddle.net/23wx9nar/7/

	var tes = document.querySelectorAll("input[id^='txtemployee']");
  tes.forEach(function(te) {
  	te.value='value';
  });

Open in new window

Author

Commented:
I tried it with chrome and it works, but I tried it with Internet Explorer 11 and it's not working.
Do you know a better way so it works on both Chrome and Internet Explorer?
probably the selector by attribute value's substring  is not  supported. Can you assign an unique class to all those input boxes (say "txtemployee_class") and select them with
var tes = document.querySelectorAll("input.txtemployee_class");

Open in new window

Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Author

Commented:
I don't think the issue is by id or by class. I tried by class and still get the same error in internet explorer.

The error message i get in internet explorer is :  Object doesn't support property or method 'forEach'

I think IE doesn't support foreach.
https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches/


Is there a way to re-write this part without using forEach?

            tes.forEach(function (te) {
                te.value = 'value'
            });
Sure,
var tes = document.querySelectorAll("input[id^='txtemployee']");
for( var i = 0; i < tes.length; i++ )
  	tes[i].value='value';

Open in new window

Author

Commented:
Thanks.

Author

Commented:
Thanks , works on chrome and ie just fine.
Michel PlungjanIT Expert
Top Expert 2009

Commented:
forEach on nodelists is indeed not supported by any IE
https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach

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