Furkat U.
Furkat U.

Reputation: 451

Meteor handle multiple input with same name

How to handle multiple input values with same name in meteor and expect array from events.

<input type="text" class="form-control valid" id="companyEmail" name="companyEmail[]">

Save multiple emails

Upvotes: 1

Views: 854

Answers (2)

Michel Floyd
Michel Floyd

Reputation: 20227

By far the easiest way to scope events in Blaze templates is to define templates at the level at which you need to trap events.

If you have:

 <template name="companyEmails">
 {{#each companyEmail}}
   <input type="text" class="form-control valid" id="companyEmail" name="companyEmail[]">
 {{/each}}
 </template>

Then if you attach an event handler to the companyEmails template you have to figure out which input was changed.

If you change this pattern to:

 <template name="companyEmails">
 {{#each companyEmail}}
   {{> oneCompanyEmail}}
 {{/each}}
 </template>

 <template name="oneCompanyEmail">
 <input type="text" class="form-control valid" id="companyEmail" name="companyEmail[]">
 </template>

Then you can attach an event handler to the lower level template and be guaranteed that you're getting the correct event on the correct object with the appropriate data context:

 Template.oneCompanyEmail.events({
   'input #companyEmail': function(ev,err){
     var emailAddress = ev.target.value;
     console.log(this); // will be the value of companyEmail from the #each
   }
 });

Upvotes: 1

Omer Weiss
Omer Weiss

Reputation: 153

As always in Meteor you're probably working in a Template scope and creating those inputs dynamically.

if that is the case you need to create an event handler for the input and then capture the concurrent used input using "this", here's an example:

html file:

<template name="emailForm">
  {{#each item in items}}
    <input name="email" class="email" placeholder="enter email address">
    <button class="addEmail">+</button>
  {{/each}}
</template>

in your js file:

if(Meteor.isClient) {
  Template.emailForm.events({
    'click .addEmail': function(event) {
      console.log(this);
    }
  });
}

take a look at what's comes out with "this" and find out how to extract your desired bit of data as it will represent only the clicked item.

Upvotes: 0

Related Questions