Nisha
Nisha

Reputation: 158

Error in processing `keyup` event

I am new to meteor, please anyone help me to solve the issue below.

Let me first be clear on what project I am working on.

I have a collection which stores user details so I want to edit user information. I am using iron-router, so that when I enter user_id in URL it displays me user details in textbox, so I can edit them.

And I am able to save edited user details when I click on "Edit" button, but I want to update details automatically, so I tried to use keyup event but it is not working.

I am getting the following error when I'm handling keyup event instead of submit:

Cannot read property 'value' of undefined at Object.keyup .sub

Below is my js code:

Router.route('/temp1/:_id', function () {
  var pid = this.params._id;
  this.render('temp1', {
    data: function () {
      return Dbs.findOne({ user_id: pid });
      Router.go("/temp1", {}, { id: pid });
    }
  });
});

Template.temp1.events({
  'keyup .sub'(event)  {
    const target = event.target;
    const user_id1 = target.user_id.value;
    const add1 = target.add.value;   
    const cont1 = target.cont.value;
    const pth1 = target.pth.value;

    var p = Dbs.findOne({ user_id: Router.current().params._id });
    Dbs.update({ _id: p._id }, {
      $set: {
        user_id: user_id1,
        cont: cont1,
        add: add1,
        pth: pth1
      }
    });
    console.log(user_id1);
    alert(user_id1);
  }
});

Html code:

  <form class="sub">
    <input type="text" name="user_id" value="{{user_id}}"/>
    <input type="text" name="add" value="{{add}}"/>
    <input type="text" name="cont" value="{{cont}}"/>
    <input type="text" name="pth" value="{{pth}}" />

    <!--<center><input type="submit" value="Submit" class="waves-effect #607d8b grey btn"></center>-->
 </form>

Upvotes: 1

Views: 136

Answers (1)

Styx
Styx

Reputation: 10086

When you're using submit .sub event — inside your handler the event.target is form, that's why constructs like target.user_id.value are working.

When you're using keyup .sub event — this keyup event is bubbling to the form from its input elements, thus event.target will point to that input which dispatched this event.

There are two ways to "fix" your issue:

  1. Use event.currentTarget instead of event.target

  2. Replace this line:

    const target = event.target;

    with this one:

    const target = $(event.target).closest('form').get(0);

    So your target variable will always point to form element.

Upvotes: 2

Related Questions