Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use JavaScript variables in jQuery selectors?
It's quite easy to use JavaScript variables in jQuery selectors. This technique allows you to dynamically target HTML elements based on values stored in variables, making your code more flexible and interactive.
Using Variables in jQuery Selectors
To use a JavaScript variable in a jQuery selector, you need to concatenate the variable with the selector string using the + operator. The basic syntax is $("selector" + variable + "selector").
Example
Let's see an example to use JavaScript variables in jQuery to hide an element ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("input").click(function(){
var name = this.name;
$("input[name=" + name + "]").hide();
});
});
</script>
</head>
<body>
<h1>Heading 1</h1>
<input type="text" id="bx"/>
<input type="button" name="bx" value="one"/>
<br>
<input type="text" id="by"/>
<input type="button" name="by" value="two"/>
<p>To hide the buttons, click on it.</p>
</body>
</html>
In this example ?
- The
var name = this.namestores the name attribute value of the clicked button - The selector
"input[name=" + name + "]"dynamically targets input elements with the matching name attribute - When you click a button, it hides itself by using its own name attribute value in the jQuery selector
Conclusion
Using JavaScript variables in jQuery selectors enables dynamic element targeting by concatenating variables with selector strings. This approach makes your jQuery code more flexible and allows for interactive user experiences.
