Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Button Text/Image using Meteor and jQuery Mobile

I'm building an App using Meteor and am a little unclear how all the code fits together using jQuery Mobile.

Basically I have an edit button in the header and when clicked I would like the content in the content section to change, and the edit button should change to say save. Clicking the save button should update the content and put the button back to it's original state.

Edit button looks like:

<a data-icon="plus" data-role="button" class="edit" >edit</a>

Here's a fiddle with no JS/JQ: http://jsfiddle.net/AU2cB/3/

The idea is show input fields when the edit button is clicked, and show the updated user inputted text when the save is clicked. I obviously haven't got to the server part of this so any advice on how to do that with Meteor would be a bonus (I have the facebook login working using {{> loginButtons }})

NB: I'm very new to all. of this. It's a relatively simple app, so in the root directory I just have 1 html file and one javascript file with if (Meteor.is_client) & if (Meteor.is_server) statements in it.

like image 345
jaybong Avatar asked Dec 27 '25 16:12

jaybong


1 Answers

Let's say your button is in a template:

<body>
  {{> editButton}}
  {{> fields}}
</body>

<template name="editButton">
  <a data-icon="plus" data-role="button" class="edit" >edit</a>
</template>

To wire this up with Meteor, attach events to the template:

Template.editButton.events({
  "click [data-role='button']": function(e) {
    if ($(e.target).text() == "edit")
      $(e.target).text("save");
    else
      $(e.target).text("edit");
  }
});

That will toggle the text of the button when you click it. So what about showing or hiding related fields? We can use Session:

Template.editButton.events({
  "click [data-role='button']": function(e) {
    if ($(e.target.text() == "edit") {
      $(e.target).text("save");
      Session.set("editing", true);
    }
    else {
      $(e.target).text("edit");
      Session.set("editing", false);
    }
  }
});

Now you need to listen to the value of editing and use it to tell Meteor whether the related fields should be shown or not:

<template name="fields">
  {{#if editing}}
    <input type="text" name="myField"/>
  {{/if}}
</template>

Template.fields.editing = function() {
  return Session.get("editing");
}

Now when you click the button, Meteor will update the value of the associated Session key, and because Session is reactive, it will rerun the Template.fields.editing function and rerender the fields template.

To save the data the user inputs, you could also use Session. I'll let you figure that part out yourself, it's pretty similar to the code I wrote here. To save user information persistently, look into Meteor.user() and Collections.

like image 76
Rahul Avatar answered Dec 30 '25 17:12

Rahul