Marko JS on-submit - javascript

I can't get this to work, it will not console.log(this.stat.first_name) , I need to know how to access the input form values that are entered so I can change state and then make an axios post request in the postSubmit function. I am doing the console.log first to test it and get data movement correct.
Anything will help.
First question was deleted, this is a repost as I did not figure the problem out.
class {
onCreate() {
this.state = {
first_name: null,
last_name: null,
email: null,
address: null,
phone_number: null,
email_promotion_optin: false
};
}
postSubmit(event) {
event.preventDefault();
this.state.first_name = event.target.name.first_name;
console.log(this.state.first_name);
}
}
<form on-click('postSubmit')>
<fieldset>
<legend> Create Customer</legend>
<div>
<label>
First Name: <input type="text" name="first_name">
</label>
</div>
<div>
<label>
Last Name: <input type="text" name="last_name">
</label>
</div>
<div>
<label>
Email: <input type="text" name="email">
</label>
</div>
<div>
<label>
Address: <input type="text" name="address">
</label>
</div>
<div>
<label>
Phone Number: <input type="text" name="phone_number">
</label>
</div>
<div>
<label>
Submit <input type="submit">
</label>
</div>
</fieldset>
</form>
UPDATE!!!!!!:
I have come up with this from MarkoJS documentation, but still no luck. I may be on the right route or I may be polluting my code with a lot of unnecessary crap.
$ const axios = require('axios');
class {
onCreate() {
this.state = {
first_name: '',
last_name: '',
email: '',
address: '',
phone_number: '',
email_promotion_optin: false
};
}
onFirstNameInput () {
this.state.first_name = this.getEl('firstName').value;
}
onLastNameInput () {
this.state.last_name = this.getEl('lastName').value;
}
onEmailInput () {
this.state.email = this.getEl('email').value;
}
onAddressInput () {
this.state.address = this.getEl('address').value;
}
onPhoneNumberInput () {
this.state.phone_number = this.getEl('phoneNumber').value;
}
postSubmit() {
axios.post('/api/v1/customers', this.state)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
}
<form>
<fieldset>
<legend> Create Customer</legend>
<div>
<label>
First Name: <input type="text" key="firstName" on-input('onFirstNameInput')>
</label>
</div>
<div>
<label>
Last Name: <input type="text" key="last_name" on-input('oneLastNameInput')>
</label>
</div>
<div>
<label>
Email: <input type="text" key="email" on-input('onEmailInput')>
</label>
</div>
<div>
<label>
Address: <input type="text" key="address" on-input('onAddressInput')>
</label>
</div>
<div>
<label>
Phone Number: <input type="text" key="phone_number" on-input('onPhoneNumberInput')>
</label>
</div>
</fieldset>
<div>
<button on-click('postSubmit')>Submit</button>
</div>
</form>

I looked into the issue. The reason that the code is not working as expected is that the properties on the this.state object are not defined as enumerable. MarkoJS uses Object.defineProperty to create getters and setters for the state properties, but it is not explicitly setting the enumerable property to true so it is defaulting to false. I think we should fix this and opened up a GitHub issue to discuss: https://github.com/marko-js/marko/issues/964
In the meantime, I recommend the following workaround to explicitly copy over the properties that should be submitted with the HTTP post:
postSubmit() {
var request = {
first_name: this.state.first_name,
last_name: this.state.last_name,
email: this.state.email,
address: this.state.address,
phone_number: this.state.phone_number,
email_promotion_optin: this.state.email_promotion_optin
}
axios.post('/api/v1/customers', request)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}

Related

How to clear the form input fileds when user successfully submitted the form in Vue.js?

i have one registration page when user renter some values ,after successfully submission the form need to be clear all the field for that i am using predefined function called reset() inside the script section ,it's not working i am unable to get where did i mistake and one more thing autocomplete="off" is also not working please help me to fix this issue.
Register.vue
<template>
<div class="main">
<div class="container">
<img src="../assets/sideImg.png" alt="notFound" />
<p>Online Book Shopping</p>
<div class="box">
<div class="headings">
<h5 class="signin">Login</h5>
<h5 class="signup">signup</h5>
</div>
<form id="myForm" #submit.prevent="handlesubmit">
<div class="fullname">
<p>FullName</p>
<input type="text" class="namebox" required v-model="FullName" autocomplete="off" pattern="[A-Za-z]{3,12}">
</div>
<div class="username">
<p>EmailID</p>
<input type="email" class="emailbox" required v-model="EmailID" pattern="^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$">
</div>
<div class="pass">
<p>Password</p>
<input :type="password_type" class="password" v-model="Password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{6,}$" required>
<i class="bi bi-eye-slash" id="togglePassword"></i>
</div>
<div class="mobile">
<p>MobileNumber</p>
<input type="tel" class="telephone" v-model="Mobile" pattern="^\d{10}$" required>
</div>
<button class="btn-section" #click="clear();" type="submit">Signup</button>
</form>
</div>
</div>
</div>
</template>
<script>
import service from '../service/User'
export default {
name: 'Register',
data() {
return {
FullName: '',
EmailID: '',
Password: '',
Mobile: '',
password_type: "password",
}
},
methods: {
togglePassword() {
this.password_type = this.password_type === 'password' ? 'text' : 'password'
},
clear(){
document.getElementById("myForm").reset();
},
handlesubmit() {
let userData = {
FullName: this.FullName,
EmailID: this.EmailID,
Password: this.Password,
Mobile: this.Mobile
}
service.userRegister(userData).then(response => {
// console.log("user Details", response);
alert("user registered successfully");
return response;
}).catch(error => {
alert("Invalid Email/Mobile number");
return error;
})
}
}
}
</script>
<style lang="scss" scoped>
#import "#/styles/Register.scss";
</style>
try this:
in your HTML
<form ref="myForm" #submit.prevent="handlesubmit">
in your handlesubmit, after it finishes
this.$refs.myForm.reset();
about autocomplete, found this:
In order to provide autocompletion, user-agents might require elements to:
Have a name and/or id attribute
Be descendants of a element
The form to have a submit button
try adding a name or id to the input.

Enable/Disable button with vueJs

new Vue({
el: '#app',
data: {
terms: false,
fullname: false,
mobile: false,
area: false,
city: false,
},
computed: {
isDisabled: function(){
return !this.terms && !this.fullname && !this.mobile && !this.area && !this.city;
}
}
})
<div id="app">
<p>
<label for='terms'>
<input id='terms' type='checkbox' v-model='terms' /> I accept terms!!!
<input id="fullname" type='text' v-modal='fullname'/> name
<input id="mobile" type='text' v-modal='mobile'/> mobile
<input id="area" type='text' v-modal='area'/> area
<input id="city" type='text' v-modal='city'/> city
</label>
</p>
<button :disabled='isDisabled'>Send Form</button>
</div>
Until user fill all the details, button should be disabled.
But Issue with this is if i click on checkbox directly button is enabling without checking for other fields
There are many problems in your code and i will list them one by one.
data property should be a function.
fullname , mobile , ... are bound to input type="text" so empty string is better for initial value.
there are typos in your v-modal
there is a mistake in your logical formula for isDisabled
so the final code should be like this:
new Vue({
el: '#app',
data() {
return {
terms: false,
fullname:'',
mobile: '',
area: '',
city: '',
};
},
computed: {
isDisabled: function(){
return !this.terms || !this.fullname || !this.mobile || !this.area || !this.city;
}
}
})
<div id="app">
<p>
<label for='terms'>
<input id='terms' type='checkbox' v-model='terms' /> I accept terms!!!
<input id="fullname" type='text' v-model='fullname'/> name
<input id="mobile" type='text' v-model='mobile'/> mobile
<input id="area" type='text' v-model='area'/> area
<input id="city" type='text' v-model='city'/> city
</label>
</p>
<button :disabled='isDisabled'>Send Form</button>
</div>
I highly recommend you to use IDE or eslint.

React js TypeError: Cannot read property 'state' of undefined [duplicate]

This question already has answers here:
Value of this in React event handler
(3 answers)
Closed 2 years ago.
I'm getting this error TypeError: Cannot read property 'state' of undefined whenever I type in the form and click submit the error occur in const createAppointment , I want to display in the console then the error occurred
Can't find a similar issue for someone else over the internet.
here is the code:
export default class createAppointment extends Component {
constructor(props){
super(props);
this.onChangeUser = this.onChangeUser.bind(this);
this.onChangeName = this.onChangeName.bind(this);
this.onChangeSpecialty = this.onChangeSpecialty.bind(this);
this.onChangePhoneNumber = this.onChangePhoneNumber.bind(this);
this.onChangeReason = this.onChangeReason.bind(this);
this.onChangeEmail = this.onChangeEmail.bind(this);
this.onChangeDate = this.onChangeDate.bind(this);
this.state={
userName:'',
name:'',
specialty: '',
phoneNumber: Number,
reason: '' ,
email:'',
date: new Date(),
users: []
}
}
componentDidMount(){
this.setState({
users:['test user'],
userName:'test user'
})
}
onChangeUser(a){
this.setState({
userName: a.target.value
});
}
onChangeName(a){
this.setState({
name: a.target.value
});
}
onChangeSpecialty(a){
this.setState({
specialty: a.target.value
});
}
onChangePhoneNumber(a){
this.setState({
phoneNumber: a.target.value
});
}
onChangeReason(a){
this.setState({
reason: a.target.value
});
}
onChangeEmail(a){
this.setState({
email: a.target.value
});
}
onChangeDate(date){
this.setState({
date: date
});
}
onSubmit(a){
// will prevent usual submit and will submit what we want
a.preventDefault();
**//here are the errors**
const appoinrment = {
userName: this.state.userName,
name: this.state.name,
specialty: this.state.specialty,
phoneNumber: this.state.phoneNumber,
reason: this.state.reason,
email: this.state.email,
date: this.state.date
}
console.log(appoinrment)
window.location = '/';
}
render(){
return(
// start form
<div>
<h3>Book an appoinrment</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Username: </label>
<select ref="userInput"
required
className="form-control"
value={this.state.userName}
onChange={this.onChangeUser}>
{
this.state.users.map(function(user) {
return <option
key={user}
value={user}>{user}
</option>;
})
}
</select>
</div>
<div className="form-group">
<label>Name: </label>
<input type="text"
required
className="form-control"
value={this.state.name}
onChange={this.onChangeName}
/>
</div>
<div className="form-group">
<label>Specialty: </label>
<select required
className="form-control"
value={this.state.specialty}
onChange={this.onChangeSpecialty}>
<option value="Orthopedics">Orthopedics</option>
<option value="Vascular">Vascular</option>
<option value="Cardiothoracic">Cardiothoracic</option>
<option value="Reconstructive">Reconstructive</option>
<option value="Oncology">Oncology</option>
<option value="Neurosurgery">Neurosurgery</option>
<option value="UrologySurgery">Urology surgery</option>
<option value="GeneralSurgery">General surgery</option>
<option value="PediatricSurgery">Pediatric surgery</option>
</select>
</div>
<div className="form-group">
<label>Phone Number: </label>
<input type="number"
required
className="form-control"
value={this.state.phoneNumber}
onChange={this.onChangePhoneNumber}
/>
</div>
<div className="form-group">
<label>Date </label>
<div>
<DatePicker
selected={this.state.date}
onChange={this.onChangeDate}
/>
</div>
</div>
<div className="form-group">
<label>Email </label>
<input
type="text"
className="form-control"
value={this.state.email}
onChange={this.onChangeEmail}
/>
</div>
<div className="form-group">
<label>Reason for visiting </label>
<textarea rows="4" cols="50" className="form-control" value={this.state.reason} onChange={this.onChangeReason}>
</textarea>
</div>
<br/>
<div className="form-group">
<input type="submit" value="Book appointment now!" className="btn btn-primary" />
<input type="reset" value="Reset" className="btn btn-primary reset"/>
</div>
</form>
</div>
// end form
)
}
}
You hav not done binding for your onSubmit inside your constructor. So the this inside onSubmit method does not refer to the class instance. and hence the error.
Just bind onSubmit
constructor(props){
super(props);
this.onChangeUser = this.onChangeUser.bind(this);
this.onChangeName = this.onChangeName.bind(this);
this.onChangeSpecialty = this.onChangeSpecialty.bind(this);
this.onChangePhoneNumber = this.onChangePhoneNumber.bind(this);
this.onChangeReason = this.onChangeReason.bind(this);
this.onChangeEmail = this.onChangeEmail.bind(this);
this.onChangeDate = this.onChangeDate.bind(this);
this.onSubmit = this.onSubmit.bind(this); //<------ here

How to check passwords match in vanilla Vue.js?

I'm new to Vue.js and I'd like to check if passwords are matched.
If they do not match, after the user leaves the confirmation field, the error text Passwords don't match! should appear.
I've seen a couple of solutions which involve using plugins, but I'm wondering what is the idiomatic way to do it using pure vue.js?
https://jsfiddle.net/Babrz/L2md63j7/3/
<div id="app">
<form >
<div class="form-group">
<input type="email" class="form-control" placeholder="Email">
</div>
<br>
<div class="form-group">
<input type="password" class="form-control" v-model="password" placeholder="Password">
</div>
<br>
<div class="form-group">
<input type="password" class="form-control" v-model="password2" placeholder="Confirm Passwrd">
</div>
<small v-if="showError">Passwords don't match!</small>
<br>
<div class="form-group">
<input type="text" class="form-control" placeholder="Age">
</div>
<br>
<button type="submit" class="btn login-btn">Register</button>
</form>
</div>
new Vue({
el: "#app",
data: {
email: '',
password: '',
password2: '',
age: 0,
showError: false
},
methods: {
toggle: function(todo){
todo.done = !todo.done
}
}
})
It sounds like you want to use an onblur event to run a validation on the two password values. A very basic implementation might look like this.
...
<input v-on:blur="validate" type="password" class="form-control" v-model="password2" placeholder="Confirm Passwrd">
...
...
new Vue({
el: "#app",
data: {
email: '',
password: '',
password2: '',
age: 0,
showError: false
},
methods: {
toggle: function(todo){
todo.done = !todo.done
},
validate: function() {
console.log(this.password === this.password2)
}
}
})
...
https://v2.vuejs.org/v2/guide/events.html
You can get a lot of help if you use something like validate.js to validate your passwords too.
http://validatejs.org

Vue/Jquery override two-way data bidning

I have an input in a Vue.js component that I need to override using jquery. I need to fill an input with an email address using jquery. When I press fill in email jQuery will populate the email input. But when I use V-model this it is not updated. Is there a workaround for this?
Here is a working jsfiddle example
https://jsfiddle.net/s3b7f1ah/
Here is the HTML
<button id="push-email">Fill in email</button>
<br><br>
<div id="root">
<label for="name">Name</label>
<input type="text" name="name" id="name" v-model="name">
<label for="name">Email</label>
<input type="text" name="email" id="email" v-model="email">
<br><br>
<button #click="proceed">next</button>
<br><br>
{{ name }} <br>
{{ email }}
</div>
Here is the jQuery
//jQuery
$(function() {
$('#push-email').click(function() {
$('#email').val("john#example.com");
});
});
And here is the vue component
//Vue
var app = new Vue({
el: '#root',
data: {
name: '',
email: '',
},
methods: {
proceed: function () {
}
},
});
https://jsfiddle.net/s3b7f1ah/
The best way if you really are stuck would be to add an event listener in your vue model:
var app = new Vue({
el: '#root',
data: {
name: '',
email: '',
},
methods: {
proceed: function () {
},
foo : function(event){
this.email = event.target.value;
}
},
});
<input #change="foo" type="text" name="email" id="email" v-model="email">
This way, you don't have to modify the jQuery logic.
Updated jsfiddle: https://jsfiddle.net/s3b7f1ah/1/
Change you jquery code to set the model value instead and it will get reflected in the input field.
//jQuery
$(function() {
$('#push-email').click(function() {
app.email = 'john#example.com';
});
});
You could write a directive to handle the jQuery change (as long as jQuery issues one). If jQuery just sets the value without triggering a change event, you'll never see it. Borrowing code from Axnyff:
//Vue
var app = new Vue({
el: '#root',
data: {
name: '',
email: '',
},
methods: {
proceed: function() {
},
foo: function(event) {
this.email = event.target.value;
}
},
directives: {
onJqueryChange: {
bind(el, binding) {
$(el).change(binding.value);
}
}
}
});
//Jquery
$(function() {
$('#push-email').click(function() {
$('#email').val("john#example.com").change();
});
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="push-email">Fill in email</button>
<br>
<br>
<div id="root">
<label for="name">Name</label>
<input type="text" name="name" id="name" v-model="name">
<label for="name">Email</label>
<input v-on-jquery-change="foo" type="text" name="email" id="email" v-model="email">
<br>
<br>
<button #click="proceed">next</button>
<br>
<br> {{ name }}
<br> {{ email }}
</div>

Categories

Resources