BlueNut
BlueNut

Reputation: 17

Getting values from each row in Meteor js

There is a table wrapped by a template. What I want to do is getting values from specified fields of this table together with the values in a form. And there is a button in each row to pass the values. But when I tried to print them out in console, it said it is undefined. So anyone has a solution to this or a better way to do it, I would really appreciate it.

So far I have tried to use serializeArray(). However, it seemed like it can't get the values from <td> element.

<template name="student">
    {{#each student}}
    <tr>
      <td>{{name}}</td>
      <td>{{studentID}}</td>
      <td><textarea rows="1"></textarea></td>
      <td><input type="submit" class="btn btn-primary markAttendance"></td>
    </tr>
    {{/each}}
</template>

<template name="subject">
    <select id="dropdown" name="dropdown" class="form-control">
    <option>Please select a subject</option>
    {{#each subject}}
    <option>{{subjectCode}}</option>
    {{/each}}
    </select>
</template>

Event handler:

Template.content.events({
   'click .markAttendance':function(e){
     e.preventDefault();
     var subjectCode = $(e.target).find('[name=dropdown]').val();
     var week = $(e.target).find('[name=week]').val();
     var studentName = $(e.target).find('td:eq(0)').text();
     var studentID = $(e.target).find('td:eq(1)').text();
     console.log(subjectCode);
     console.log(week);
     console.log(studentName);
     console.log(studentID);
     //.....
   }
 });

Upvotes: 0

Views: 142

Answers (2)

James
James

Reputation: 512

I use https://viewmodelblaze.azurewebsites.net/blaze with Blaze, it make this kind of this super simple, but without it you could:

Add a data-studendid to the input

<td><input type="submit" class="btn btn-primary markAttendance" data-studentid="{{studentID}}"></td>

You can then query the student by ID in your method handler, ie: Students.findOne({_id: studentId})

Upvotes: 0

Derrick Gremillion
Derrick Gremillion

Reputation: 268

    Template.content.events({
      'click .markAttendance':function(event, instance){
       e.preventDefault(); // not needed unless you have a form someplace I'm not seeing
       var student = this;
       var subjectCode = $('#dropdown').val();
       var week = $('[name=week]').val();
       var studentName = student.name;
       var studentID = student._id;
       console.log(subjectCode);
       console.log(week);
       console.log(studentName);
       console.log(studentID);
     //.....
   }
});

Upvotes: 1

Related Questions