event.target is undefined in events
Asked Answered
P

2

17

How can one use each input values in events? Hope my below code will explain you well.

HTML:

<template name="UpdateAge">
    {{#each Name}}
    <div data-action="showPrompt">
       <div>
          Some content
       </div>

       <div>
         <div>
            Some content
         </div>
       </div>
       <div>
           Name : {{name}}
           Age : <input type="text" name="age" value="{{age}}"/> //I need to access age values in event
       </div>
    </div>
{{/each}}
<template>

JS:

Template.UpdateAge.events({
  'click [data-action="showPrompt"]': function (event, template) {
        console.log(event.target.age.value); // TypeError: event.target.age.value is undefined
  }
});

I dont know whether my approach is good for passing parameter values to events so suggestions are welcome.

Pangenesis answered 20/5, 2015 at 7:20 Comment(2)
Well, your error message doesn't say that event.target was undefined, does it? However, hardly any target does have an .age property, so accessing .value there would throw.Tell
Yeah, still the <div> does not magically gain a .age property by that.Tell
M
21

the notation you are using is valid only for form elements and when event.target IS a form element.

event.target.age.value

event.target is the element where the event occurred, event.currentTarget is the element which has attached the event handler

if you replace div with form and replace target with currentTarget then it will work

event.currentTarget.age.value

here a fiddle using your code

Macro answered 20/5, 2015 at 7:35 Comment(3)
I changed div to form but same error occurs. I think am not submitting the form. In my case I don't have submit button.Pangenesis
event.target is the element on which you clicked. so if you click on the input box event.target is the the input box, not the form. the form element will be currentTargetMacro
Thanks, best way for me, works perfectly. This saved my life :)Ludicrous
F
1

If the event is bound on the container div then the input should be searched from target, because event.target would give you the element whom the event was attached to.

To access any value within the div you must first get access to that element and then use the properties of that element to access whatever needed - .value in this case.

Ferri answered 20/5, 2015 at 7:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.