Reputation: 1024
I have a number of variables containing text strings and want to select which should be shown based on the element that is clicked.
The code below is a very simplified version of what I'm trying to do, at the moment it sets the innerHTML of .msgBox to 'A_msg' or 'B_msg', what I want it to do is set it to the value of those variables.
var A_msg = "You clicked A";
var B_msg = "You clicked B";
$(".trigger").mouseover(function() {
var MsgToDisplay = $(this).attr('id')+"_msg";
$('#msgBox').html(MsgToDisplay);
});
<div class="trigger" id="A">Option A</div>
<div class="trigger" id="B">Option B</div>
<div id="msgBox"></div>
Upvotes: 3
Views: 2788
Reputation: 887449
You should use an object:
var messages = {
A: "You clicked A",
B: "You clicked B"
};
$(".trigger").mouseover(function() {
var MsgToDisplay = messages[$(this).attr('id')];
$('#msgBox').html(MsgToDisplay);
});
You can write messages[someString]
to get the value of property by name.
Upvotes: 8