Get input value after click event on an <a class='btn btn-message'>?


#1

I’ve been at this problem for awhile now, the tricky part of this is that a new card is generated each time a fixed-action button is clicked, so I can’t really use document.getElementById since it seems to only get the first input from the generated card. Instead I’ve been trying to do this instead:

console.log($(event.target).closest(‘input’).find(’.user_name’).val);

but it returns the tag element instead:
> <a class="waves-effect waves-light btn btn-message purple accent-1" style="color: rgb(106, 27, 154);">Message</a>

> <html>
>     <div class="card horizontal">
>       <div class="card-stacked">
>         <div class="card-content"  style="font-size:21px">
>           {{> username_input}}
>         </div>
>         <div class="card-action">
>           <a class="waves-effect waves-light btn btn-message purple accent-1">Message</a>
>         </div>
>       </div>
>     </div>

> <template name="username_input">
>   <div class="input-field col s4">
>           <input placeholder="" name="user_name" id="user_name" type="text" class="validate user_name">
>           <label for="user_name">Name</label>
>           </div>
> </template>
> </html>

Here is the javascript I’m using to get the

Template.user.events({
‘click .btn-message’: function(event, Template) {
console.log(event.target);
event.target.style.color=’#6a1b9a’;
console.log($(event.target).closest(‘input’).find(’.user_name’).val);
}
});

but I’m rendering a new card to a container using this javascript function:

Template.fab.events({
‘click .fab-btn’: function () {
console.log(‘fab button clicked’);
var my_container = document.getElementById(‘container’);
var rendered_template = Blaze.render(Template.user,my_container);
}
});

What’s the proper way to get the input value in my case? :sweat:


#2

I’m OP, problem solved! Answer is in my call to get the input.

console.log($(event.target).closest(’.card-stacked’).find(’.user_name’).val());

From the documentation of .closest and .find:
The .closest selector traverses up the DOM to find the parent that matches the conditions.
the .find selector traverses down the DOM where the event occurred, that matches the conditions.

Since my original code was looking for input which is not up the domain, it wouldn’t be able to find the with .val.
Also I made a mistake with .val not having the brackets (), it should be .val(). Otherwise it would return the source code behind the function .val.