how to take value from input with vue.js? - javascript

I need some enlightenment.
Right now, I'm learning vue.js, and I want to know how to take all data value from input form?? I want take all data from there & save into my database. But, I still don't know, how to get all these data.. thx
<div id="example-1">
<form>
<input v-model="info.name">
<input v-model="info.nickname">
<input v-model="info.gender">
<input type="submit" name="" value="Submit" v-on:click="submitData">
</form>
</div>
<script>
var example1 = new Vue({
el: '#example-1',
data: {
info: {
name: '',
nickname: '',
gender: ''
}
}
},
methods: {
submitData: function() {
console.log(this.info);
// this.$http.post('/api/something', JSON.stringify(this.info));
}
})
</script>

I bet you need to prevent the default action. When you submit a form, the page automatically reloads. You won't ever see a response from the server in the console because it will clear when the page refreshes after the submission action.
Go here, and ctrl + f 'Event Modifiers'. You'll want to use .prevent in this case, then write your own code to handle the submission / response.

Related

I've got a weird behaviour on req.body on put request on a specific field

I've created a form to save a new real estate to MongoDB, using multer for multi-part form data and body-parser.
Everything works fine except the "rooms" in the "put" (EDIT) route, which are returned as an array, instead of a single value, which makes absolutely no sense, as everything else works just fine.
I've tried to translate the data from the array to a single numerical value, but that does not work as if I try to edit the document once more the new value is pushed in the array instead of replacing the old one.
//EDIT PUT ROUTE
router.put("/immobili/:_id/edit",
upload.fields([{ name: 'estateImages', maxCount: 30 },
{ name: 'document', maxCount: 1 }]),
(req, res) => {
// IMAGES LOGIC SKIPPED HERE AS NOT PERTINENT
Estate.findOneAndUpdate({ _id: requestedId }, {
rooms: req.body.rooms, //BUGGED
squareFeets: req.body.squareFeets, //WORKS CORRECTLY
//CALLBACK ...
}}
// result of console.log of req.body.rooms and req.body.squareFeets
rooms: [ '2', '' ],
squareFeets: 120
//EJS FORM DATA
<form action="/estates/<%= estate._id %>/edit?_method=PUT" method="POST"
enctype="multipart/form-data">
//INPUT NOT WORKING:
<input name="rooms" value="<%= estate.rooms %>"></input>
//INPUT THAT WORKS:
<input name="superficie" value="<%= estate.squareFeets %>"></input>
<input type="submit" value="Publish">
</form>
When you get an array, is because you have multiple inputs with that name:
<input name="rooms" value="<%= estate.rooms %>"></input>
<input name="rooms" value="other-value"></input>
So if you don't want an array, change the input name to the second one.
Omg I have been SO stupid, I've put two inputs with the same name value in the form, thus those values were being saved as an array.
I'm so sorry about this. Thanks for your time!

Using v-bind and v-on instead of v-model vuejs

I was using v-model to handle inputs in a form, I had to change it to bind props values, at first input was like
<input type="text" class="form-control" placeholder="" v-model="username">
and now it looks like
<input type="text" class="form-control" placeholder="" v-bind:value="modelData.username" v-on:input="username = $event.target.value">
modelData is coming in props. and it has username.
when Using model, in data, i had defined
data: () => {
return {
username: ""
}
},
and It was working fine, but after changing it to v-bind and v-on,
My question is how I can now get the value of username in methods? as in past, I was getting it as this.username to get the value and also clear it as well but now how I can get username in
methods: {}
I have a button to save input
<button class="btn btn-secondary" type="button" #click="validateFormAndSave($event)">Save</button>
When validateFormAndSave get called I can have this.username right now I cannot get the value? But the Vue Doc says v-model and v-bind:value& v-on:input are the same?
UPDATE:
There can be and cannot be some value already there in username, as it being filled with props value, So v-on:input="username = $event.target.value" don't get the already written value but the only new one you entered? or edit it? Why is it so? is there any method for just to get what anyone typed in there or already been typed?
UPDATE:
This is getting very ambiguous. So for now.
1. I can set v-bind:value, But I cannot get it in methods without editing it.
2. I cannot set this.username = "" and it will not be removed from input as well.
3. #input only get what you newly typed not what already in there
v-model is just syntax sugar for =>
<input :value="modelValue" #input="modelValue = $event.target.value"/>
If you want something else, it's very easy to do. Just change the update side to onInput:
<input
class="form-control"
:value="username"
#input="username = $event.target.value"
>
Then
data: () => {
return {
username: ""
}
},
mounted()
{
this.username = this.modelData.username;
},
methods:{
consoleUsername() {
console.log(this.username);
}
}
The best possible solution can be when you are getting your data from props and also loading it a form for v-models.
Using watch feature of Vue component.
First I added props as
export default {
props: ["vendorModelData"],
and then I pass it through the watch to v-model
watch: {
vendorModelData() {
this.updatePropsValue(this.vendorModelData)
console.log("data updated")
}
},
in this way, it always loads differently when Props get changed. This way I got be using v-model as well as load data from props to it.
I found it useful for me.

How do I submit a real-time validated form with Semantic UI and Meteor?

I have run into a huge problem with my form, which I validate in real time using Semantic UI.
The HTML:
<form class="ui form pin-form">
<div class="field">
<label>Email</label>
<input placeholder="name#example.com" name="email_input" type="text">
</div>
<div class="ui buttons">
<input type="submit" class="ui submit positive disabled button login-button" value="Log in">
</div>
</form>
I added the <form> tag myself and made the submit into an input so that I could access the regular submit form.
The real time validation comes from Semantic UI and a Meteor package: https://github.com/avrora/live-form-validator
On template render I do this:
if (!this._rendered) {
this._rendered = true;
pinForm = $('.ui.form.pin-form');
pinForm.form({
my_text_input: {
identifier: 'email_input',
rules: [
{
type: 'empty',
prompt: 'Type your email address'
},
{
type: 'email',
prompt: 'This is not yet a valid email address'
}
]
}
},
{
inline: true,
on: 'blur',
transition: 'slide down',
onSuccess: function () {
var submitButton = $('.ui.submit.button')
submitButton.removeClass('disabled')
return false
},
onFailure: function() {
var submitButton = $('.ui.submit.button')
submitButton.addClass('disabled')
}
})
}
The big problem here is that with return false it doesn't submit the form at all even when click the submit button, and without it it submits the form in real time, which I don't want!
Can anyone see a workaround or do I need to switch validation somehow?
If you want to do a Meteor.call, you could try doing it in the onSuccess function. The package does ask you to save the data manually within the onSuccess function.
The following code logged the email twice.
onSuccess: function () {
console.log("Email: ", $("input[name=email_input]").val());
// Submit your form here using a Meteor.call maybe?
return false;
},
You could alternatively look at aldeed:autoform for handling forms in Meteor.
This could be the stupidest question on all of SO. (Don't worry, I asked the question so I'm only dissing myself!)
Semantic UI literally provides the on: change setting, which will validate the form in real time instead of on: blur which it is set to now.
Oh, man...

ember js form submit to view

With emberjs (1.0.0rc1) and ember-data (very recent build #36d3f1b), I am trying to setup a basic crud example. I can't figure out how to retrieve a submitted model from a view and then update/save it. Here is what my code looks like:
App = Ember.Application.create();
App.Router.map(function() {
this.resource('posts', function() {
this.route('create');
this.route('edit', {
path: '/:post_id'
});
});
});
App.PostsIndexRoute = Ember.Route.extend({
model: function() {
return App.Post.find();
}
});
App.PostsCreateView = Ember.View.extend({
submit: function () {
console.log(this.get('model')); // undefined
}
});
App.Post = DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string')
});
App.Post.FIXTURES = [{
id: 2,
title: 'a',
body: 'aa'
}, {
id: 5,
title: 'b',
body: 'bb'
}];
App.Store = DS.Store.extend({
revision: 11,
adapter: DS.FixtureAdapter.create({
simulateRemoteResponse: false
})
});
and the create template:
<script type="text/x-handlebars" data-template-name="posts/create">
{{#view App.PostsCreateView tagName="form" classNames="form-horizontal"}}
<h3>Create</h3>
<div class="control-group">
<label class="control-label" for="title">Title</label>
<div class="controls">
<input type="text" id="title" placeholder="Title" />
{{view Ember.TextField valueBinding="title"}}
</div>
</div>
<div class="control-group">
<label class="control-label" for="body">Body</label>
<div class="controls">
<input type="password" id="body" placeholder="Body" />
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn">Create</button>
</div>
</div>
<div>{{#linkTo 'posts'}}Back{{/linkTo}}</div>
{{/view}}
</script>
How can I access the value of the form (serialized to the model) from the submit hook? Secondly, how do I then persist this via the FixtureAdapter?
The first part of your question is tricky to answer because it's actually pretty simple, but in order for it to be simple you'll need to change the way you think about model CRUD. Your "submit" function is not needed. When you instantiate a view) it should have an instance of your model bound to it. (If you're creating a new one it will be a new, empty instance.) When you make changes to that model in the view, they are made instantly; no need for submit. (After all, what would you submit to?)
I'm not sure this actually answers your question, but maybe it puts you on a track to answering it.
I can be a lot more definite about your second question, persisting a value via the FixturesAdapter: you can't. The FixturesAdapter is just that, an adapter for loading fixtures (essentially read-only data) into the store. Changes made to models from the FixturesAdapter will only last until the app is reloaded. To persist data you will need to transition from the FixturesAdapter to a different adapter (probably the RestAdapter).
this article deals with building a small example app including a creation form (it's originally in portuguese, but fortunately, google translate doesn't garble the text too much in this case).
the code can be found here (the important part is way down the page) and a live example here.

Best way to handle re-rendering a view in backbone.js?

I have the following view:
Main.Views.Login = EventQ.View.extend({
events: {
"submit form": "login"
},
template: "login",
login: function(e) {
var me = this;
$.ajax({
url: "/api/users/login",
type: 'POST',
dataType: "json",
data: $(e.currentTarget).serializeArray(),
success: function(data, status){
EventQ.app.router.navigate('dashboard', true);
},
error: function(xhr, status, e) {
var result = $.parseJSON(xhr.responseText);
me.render_with_errors(result.errors);
}
});
return false;
},
render: function(done) {
var me = this;
// Fetch the template, render it to the View element and call done.
EventQ.fetchTemplate(me.template, function(tmpl) {
me.el.innerHTML = tmpl(me.model.toJSON());
done(me.el);
});
},
render_with_errors: function(errors) {
var me = this;
// Fetch the template, render it to the View element and call done.
EventQ.fetchTemplate(this.template, function(tmpl) {
me.el.innerHTML = tmpl(errors);
});
}
});
and a simple template like this:
<form>
<input name="username" />
<input name="password" />
<button type="submit" />
</form>
what I'm looking to do is be able to re-render the template if errors are returned but keep the input's populated. An error template would like like:
<form>
<input name="username" />
<label class="error">required</label>
<input name="password" />
<button type="submit" />
</form>
Is there a way to bind the view to a model or something that I can check? Right now the render_with_errors works except for the fact that I lose all the data filled out on the form.
It's common for people to get in the mode where they only way they think that the only way they can change the page is a full re-render of a template. But rendering templates are only 1 solution to updating the page. You are still free to use traditional methods from within your backbone view. So another possible solution is for you to simply adjust the dom from your view.
So make your template be the following:
<form>
<input name="username" />
<label class="error" style="display:none">required</label>
<input name="password" />
<button type="submit" />
</form>
And then make the following change in your login function:
error: function(xhr, status, e) {
var result = $.parseJSON(xhr.responseText);
me.showLoginError();
}
showLoginError: function() {
this.$('.error').show();
}
And of course you can always add more to that, message customizations, etc.
It's just important to remember that full template renders aren't the only way for your backbone code to react to changes in the application state, and it's ok to manipulate the DOM in a method other than render.
Supposed you have a Model like this:
Main.Models.LoginModel = EventQ.Model.extend({
/* ... */
defaults: {
'username': "",
'password': ""
},
/* ... */
When your Ajax-Request successes, you can navigate to the next page.
If it fails, you can set your model to use undefined to indicate a missing value:
// assumed you did not enter your password
this.me.model.set( { 'username': textBoxValueSoFar, 'password': undefined });
Then can built up an template like this (it will be the same as on first page load):
<form>
<input name="username" value="{{username}}" />
{{#unless username}}
<label class="error">required</label>
{{/unless}}
<input name="password" value="{{password}}" />
{{#unless password}}
<label class="error">required</label>
{{/unless}}
</form>
{{unless}} checks if, the value is not false, undefined, null or []. So on first page load, it is an empty string and no error message is provided.
See http://handlebarsjs.com/ the part with "unless" for more details.
So what you do is: you use an empty string to indicate that no wrong value has been entered so far. You use undefined to check if a wrong value (in fact, nothing) has been entered.
In your template you can check for this an act appropriately.

Categories

Resources