Search code examples
javascriptmeteordom-eventsmeteor-blaze

How to handle button click events in meteor?


I have a meteor template:

<template name="createDefaultTemplate">

    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title"> Select Role of router</h4>
        </div>

        <div class="btn-group btn-group-justified" id="routerType">
            <a href="{{pathFor route="edgeRouterAvailablePGTemplate"}}" id= "edge" class="btn btn-default">Edge Router</a>
            <a href="{{pathFor route="aggrRouterAvailablePGTemplate"}}" id= "agg" class="btn btn-default">Aggr. Router</a>
            <a href="{{pathFor route="coreRouterAvailablePGTemplate"}}" id= "core" class="btn btn-default">Core Router</a>
        </div>
    </div>

I'm trying to pull the value of the button clicked so that I can trigger a new route. Unfortunately, I'm unable to get it right. I've tried the below, but it does fetch the value from the button.

Template.createDefaultTemplate.events({
    'click #agg ': function(event){
        console.log(event);
        var selectValue = $(event.target).val();
        console.log(selectValue + "is selected  - message logged in events");
        Session.set("selectedSchema",selectValue);
        console.log(Session.get("selectedSchema")+ " is session variable set - message logged in events");
    }
});

I've also tried something like :

 'click' : function(event)
'click a .btn .btn-default' : function(event)

But none of them seem to have any effect. I'm able to get a reading of console.log(event) but I'm unable to extract the value after clicking.

How do I fix this?


Solution

  • If i understand your question very well. You need to get a value attach to each of the buttons. You can achieve that by using the data attribute of html element

     <div class="btn-group btn-group-justified" id="routerType">
            <a href="{{pathFor route="edgeRouterAvailablePGTemplate"}}" id= "edge" data-value="6" class="btn btn-default">Edge Router</a>
            <a href="{{pathFor route="aggrRouterAvailablePGTemplate"}}" id= "agg" data-value="65" class="btn btn-default">Aggr. Router</a>
            <a href="{{pathFor route="coreRouterAvailablePGTemplate"}}" id= "core" class="btn btn-default">Core Router</a>
        </div>
    

    To get back the value on a template button click event you can simply do this.

        var selectValue = $(event.target).data('value')