I am new to node and ejs, I have below code, and need to know how to get the values from EJs file to post it to mongoDB
EJS file
<form>
<p>
<label for="username"> Username </label>
<input type="text" for="username"/>
</p>
<p>
<label for="password"> Password </label>
<input type="password" for="password" />
</p>
<p>
<label for="email"> Email </label>
<input type="text" for="email"/>
</p>
<button type="submit">Log In</button>
</form>
JS file
$('form').on('submit', function(){
var item = $('form input');
var user = [{username:item.val()},{password:item.val()},{email:item.val()}];
console.log(user);
$.ajax({
type: 'POST',
url: '/register',
data: user,
success: function(data){
//do something with the data via front-end framework
console.log(data);
location.reload();
}
});
return false;
});
As of now when I insert to mongo DB I get a new uuid but the values are going in as "0"
please aasist
So the line var item = $('form input');
is actually a collection of each input, while the line var user = [{username:item.val()},{password:item.val()},{email:item.val()}];
is only grabbing the value of the first one (this is because of how jQuery can appear to hide a collection), instead I would try this (assuming you wanted to grab specific values out of that form):
var items = $('form');
var user = {
username: $('[name=username]', items).val(),
password: $('[name=password]', items).val(),
email: $('[name=email]', items).val()
};
With following change to your html
<form>
<p>
<label for="input-username"> Username </label>
<input type="text" id="input-username" name="username"/>
</p>
<p>
<label for="input-password"> Password </label>
<input type="password" id="input-password" name="password" />
</p>
<p>
<label for="input-email"> Email </label>
<input type="text" id="input-email" name="email"/>
</p>
<button type="submit">Log In</button>
</form>
Also the for
attribute in the <label>
element is to associate with an <input>
that has an id
attribute with the same value. So considering that id
s should be unique and only resolve to a single element I would suggest adding some kind of name spacing like input-
to them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.