How to use JavaScript variables in jQuery selectors?


It’s quite easy to use JavaScript variables in jQuery selectors.

Example

Let’s seen an example to use JavaScript variables in jQuery to hide an element:

Live Demo

<!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>

Updated on: 19-Dec-2019

535 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements