So I have three buttons, each with an ID. If clicked, it would display its corresponding data which is in an array of string.
Here’s a general idea of how I think I can achieve it. (I am in the earliest stage of Javascript.)
- ID name must be a substring of its corresponding data.
- Get the ID of the clicked button and store it in another variable.
- Check which of the array items includes the ID name (through the variable) using loop.
- Once found, display data in that array index.
The problem is, I can’t figure out how to check if the array items have a substring STORED IN A VARIABLE.
All I found online was that they include the substring in the includes() function itself.
Is it possible to use a variable? How?
Is there a better approach?
Here’s my code.
Thank you.
codes
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<p id="demo"></p>
<a class="btn" href="#" id="john">John</a>
<a class="btn" href="#" id="jake">Jake</a>
<a class="btn" href="#" id="taylor">Taylor</a>
<script>
$('.btn').on('click', function () {
var name = new Array(
"John Name",
"Jake Name",
"Taylor Name"
);
var id = $(this).attr('id');
var i;
var n;
for (i = 0; i < name.length; i++) {
n = name[i].includes("id");
if (n == true) {
document.getElementById("demo").innerHTML = name[i];
break;
}
else {
//do nothing
}
}
});
</script>
</body>
</html>