Search code examples
javascriptbuttonmeteorclickhtmltext

Change button text in Meteor with JS


My button on click show and hide div that contains comment section. Now I want to make him to change text on click. So, you click once and you can see comments but instead of 'Show comments' hes text now needs to be 'Hide comments'. I tried several solutions that I found on internet and a couple of solutions that were logic to me but it's not working. I tried this too but it says that SetSession is not defined.

Template:

<template name="PrikažiMe">

<button class="PrikažiKomentar"> {{текст}} </button>

</template>

JS

if (Meteor.isClient) {


  /*  Template.PrikažiMe.onCreated(function() {
        Session.set(текст , 'Прикажи коментаре');  // <---- This part makes like everything is unpublished
    }); */


    Template.PrikažiMe.events({
      'click .PrikažiKomentar': function(){

        if (document.getElementById(this._id).style.display == "none") 
            { document.getElementById(this._id).style.display = "inline-flex", SetSession (текст, 'Сакриј коментаре');}
        else {document.getElementById(this._id).style.display = "none", SetSession (текст, 'Прикажи коментаре'); }
      }, 
    });  

    Template.PrikažiMe.helpers({   
      текст: function(){
        return Session.get(текст);
      },
    });      
};

Solution

  • So, I found out what was the problem. Hope this will help someone in the future. Look at the code:

    Template:

    <button class="PrikažiKomentar"> {{#if текст}}Сакриј коментаре {{else}} Прикажи коментаре {{/if}} </button>
    
    </template>
    

    JS:

    if (Meteor.isClient) {
    
        Template.PrikažiMe.onCreated(function PrikažiMeOnCreated() {
            this.текст = new ReactiveVar(false);
        }); 
    
        Template.PrikažiMe.events({
          'click .PrikažiKomentar': function(event, template){
            if (document.getElementById(this._id).style.display == "none") 
                { document.getElementById(this._id).style.display = "inline-flex", template.текст.set( true );}
            else {document.getElementById(this._id).style.display = "none", template.текст.set( false );}
          }, 
        });  
    
       Template.PrikažiMe.helpers({   
           текст: function() {
                  return Template.instance().текст.get();
           },
        });      
    };