Fred J. February 2016

getting the text inside a tag from meteor expression

The code below suppose to get the text insdie of the list, so if task1 is clicked then an alert should say task1, if task2 is clicked, then the alert says text2...
But when I click on any of the link, no alert shows up let along its message. I must be doing something wrong. Pleas help. Thanks

Template.mainMenu.helpers({
  menuItems: [
    {menuItem: "task1"},
    {menuItem: "task2"},
    {menuItem: "task3"},
    {menuItem: "task4"},
    {menuItem: "task5"},
    {menuItem: "task6"},
    {menuItem: "task7"}
    ]
});

Template.mainMenu.events({
  'click .menuItem': function(){
    alert(event.target.menuItem.value);
  }
});
<template name="mainMenu">
  <div class="container">
    <div class="row">
      <section class="col-xs-12">
        <div class="list-group">
          {{#each menuItems}}
            <a href="#" class="list-group-item menuItem">
              <img src="/abc.png">
              {{menuItem}} <span class="badge">&#x3e;</span>
            </a>
          {{/each}}
        </div>
      </section>
    </div>
  </div>
</template>

Answers


Kuba Wyrobek February 2016

You haven't defined argument (event) of function. Below example will help you understand that your code was throwing uncaught errors.

Template.mainMenu.events({
  'click .menuItem': function(event){
     try{
       alert(event.target.menuItem.value);
     } catch (e){
       alert(e)
     }
  }
});

Update

Add data-value={{menuItem}} to link and then try to get this value using jQuery:

<template name="mainMenu">
  <div class="container">
    <div class="row">
      <section class="col-xs-12">
        <div class="list-group">
          {{#each menuItems}}
            <a href="#" class="list-group-item menuItem" data-value={{menuItem}}>
              <img src="/abc.png">
              {{menuItem}} <span class="badge">&#x3e;</span>
            </a>
          {{/each}}
        </div>
      </section>
    </div>
  </div>
</template>

Template.mainMenu.events({
  'click .menuItem': function(event){
     try{
       alert($(event.currentTarget).data('value'));
     } catch (e){
       alert(e)
     }
  }
});

Post Status

Asked in February 2016
Viewed 1,155 times
Voted 4
Answered 1 times

Search




Leave an answer