Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - treating a string as a variable name and returning its value

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>
like image 554
Hill79 Avatar asked Aug 26 '26 13:08

Hill79


1 Answers

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.

like image 76
SLaks Avatar answered Aug 28 '26 03:08

SLaks