+ 1

How to load a variable name as id or class name to javascript selector? Anybody know better way

X=100; Var s=['s1', 's2']; $(s[0]).val(x) ;

28th Sep 2020, 9:40 AM
Thamarai Selvan
Thamarai Selvan - avatar
1 Réponse
0
Are you trying to copy x to the values of both elements identified by s1 and s2? If that's what you mean, this will work: If s1 and s2 are id's: $('#s1, #s2').val(x); If s1 and s2 are classes: $('.s1, .s2').val(x); jquery selectors can represent any number of elements so val can operate on multiple elements in one call. The comma in a CSS selector basically means "or" or "union". The code in your question won't select any elements because s1 isn't a valid tag name. A couple more minor points about your code are: - "Var" should be replaced with "var". - "x" needs to be a consistent case. X and x aren't the same.
28th Sep 2020, 8:50 PM
Josh Greig
Josh Greig - avatar