How do I use JavaScript variables as a parameter in a jQuery selector?
ES6 String Template
Here is a simple way if you don't need IE/EDGE support
$(`input[id=${x}]`).hide();
or
$(`input[id=${$(this).attr("name")}]`).hide();
This is a es6 feature called template string
(function($) {
$("input[type=button]").click(function() {
var x = $(this).attr("name");
$(`input[id=${x}]`).toggle(); //use hide instead of toggle
});
})(jQuery);
String Concatenation
If you need IE/EDGE support use
$("#" + $(this).attr("name")).hide();
(function($) {
$("input[type=button]").click(function() {
$("#" + $(this).attr("name")).toggle(); //use hide instead of toggle
});
})(jQuery);
Selector in DOM as data attribute
This is my preferred way as it makes you code really DRY
// HTML
//JS
$($(this).data("input-sel")).hide();
(function($) {
$(".js-hide-onclick").click(function() {
$($(this).data("input-sel")).toggle(); //use hide instead of toggle
});
})(jQuery);