Event click give me undefined value

I created a form that accept text input in the field. there’s 2 way to submit it. by pressing enter or clicking the submit button.
enter is fine but when i used the submit button it gives me undfined value.

here is the code:

body.html

<body>
	<h1>Welcome</h1>
	{{> blog}}
</body>

<template name="blog">
	<form class="new-blog">
		<label>Title</label>
		<input type="text" placeholder="text" name="title">
		<button type="button" class="submit-button">Submit</button>
	</form>
</template>

body.js

Template.blog.events({
	'submit .new-blog'(e) {
		e.preventDefault();
		var title = e.target.title.value;

		Blogs.insert({ 
			title: title
		});
		alert(title);

	},

	'click .submit-button'(e) {
		e.preventDefault();
		var title = e.target.title.value;

		Blogs.insert({ 
			title: title
		});
		alert(title);

	},
});

thanks in advance

In the first one, you listen for the event on the <form>, so e.target will refer to the form, and you can use e.target.title.value.

In the second one, you listen for the event on the <button>, so e.target will refer to the button, and you can’t use e.target.title.value to read what the user has entered in the <input>.

The simples solution is to skip the second event listener and change <button type="button"...> to <button type="submit"...>. This way, the form will be submitted when the user clicks on the button, which in turn fires your first event listener.

3 Likes

@Peppe_LG thanks! i understand now how form and button works together