I'm trying to create a form, the user insert data and i should show the data in another page just using vue js
I wrote this form
<form
id="main-contact-form"
class="contact-form row"
name="contact-form"
method="post"
>
<div class="form-group col-md-6">
<input
v-model="this.$store.state.name"
type="text"
name="name"
class="form-control"
required="required"
placeholder="اسم المنتج"
/>
</div>
<div class="form-group col-md-6">
<input
v-model="this.$store.state.price"
type="text"
name="email"
class="form-control"
required="required"
placeholder="السعر"
/>
</div>
<div class="form-group col-md-6">
<select
name="subject"
class="form-control"
v-model="this.$store.state.sub"
>
<option value="1">اكسسوريز</option>
<option value="2">عنايه</option>
<option value="3">مكياج</option>
<option value="4">شنط</option>
<option value="5">عطور</option>
<option value="6">اجهزه</option>
<option value="7">ملابس نساء</option>
<option value="8">رجال</option>
</select>
</div>
<div class="form-group col-md-6">
<input
:value="img"
type="file"
name="image"
class="form-control"
placeholder="اختر صورة المنتج"
/>
</div>
<div class="form-group col-md-12">
<textarea
v-model="this.$store.state.message"
name="message"
id="message"
required="required"
class="form-control"
rows="8"
placeholder="وصف المنتج أو نبذة عنه"
></textarea>
</div>
<div class="form-group col-md-12">
<input
#submit.prevent="this.$store.state.add"
type="submit"
name="submit"
class="btn btn-primary pull-right"
value="اضافة"
/>
</div>
</form>
this is my data and function i import them from store
export default createStore({
state: {
name: "",
price: "",
sub: "",
img: "",
message: "",
date: "new Date(Date.now()).toLocaleString()",
pro: [],
add: function () {
var New = {
nName: this.name,
nPrice: this.price,
nSub: this.sub,
nImg: this.img,
nDate: this.date,
};
this.name = "";
this.price = "";
this.sub = "";
this.pro.push(New);
alert(5);
// this.$router.push("/control-panel");
},
},
mutations: {},
actions: {},
modules: {},
});
When I press the button, i have this error
( Cannot POST /add-new-product ),
what should i do or what's the wrong with my code
"add" function should not be at "state" object but moved into "actions"
since it calls (as I can guess) an api to save the object
"generally if you want to modify/mutate your state, you do that in functions declared in mutations:{} and if you make api calls which are asychronous operations you declare functions in actions:{}"
e.x.
export default createStore({
actions:{
add:function(context,params){
return new Promise(function(resolve){
//call your api with ajax, assume that it returns correct
//commit your object to "add" function of mutations
context.commit('add',params);
});
}
}
})
after "add" actions returns successfully from the "api" request then you should have another
"add" function in mutations which will mutate your "pro" attribute of state
and any other "state" attributes/properties
e.x.
mutations:{
add:function(state,obj){
state.name = "";
state.price = "";
state.sub = "";
state.pro.push(obj);
alert(5);
}
}
rewrite also your vue "Form" component by adding an "submit" method (which will call the "store action") as follows and move to the "form" tag
<template>
<form #submit.prevent="submit"
id="main-contact-form"
class="contact-form row"
name="contact-form"
method="post"
>
<div class="form-group col-md-6">
<input
v-model="this.$store.state.name"
type="text"
name="name"
class="form-control"
required="required"
placeholder="اسم المنتج"
/>
</div>
<div class="form-group col-md-6">
<input
v-model="this.$store.state.price"
type="text"
name="email"
class="form-control"
required="required"
placeholder="السعر"
/>
</div>
<div class="form-group col-md-6">
<select
name="subject"
class="form-control"
v-model="this.$store.state.sub"
>
<option value="1">اكسسوريز</option>
<option value="2">عنايه</option>
<option value="3">مكياج</option>
<option value="4">شنط</option>
<option value="5">عطور</option>
<option value="6">اجهزه</option>
<option value="7">ملابس نساء</option>
<option value="8">رجال</option>
</select>
</div>
<div class="form-group col-md-6">
<input
:value="img"
type="file"
name="image"
class="form-control"
placeholder="اختر صورة المنتج"
/>
</div>
<div class="form-group col-md-12">
<textarea
v-model="this.$store.state.message"
name="message"
id="message"
required="required"
class="form-control"
rows="8"
placeholder="وصف المنتج أو نبذة عنه"
></textarea>
</div>
<div class="form-group col-md-12">
<input
type="submit"
name="submit"
class="btn btn-primary pull-right"
value="اضافة"
/>
</div>
</form>
</template>
<script>
export default{
methods:{
submit:function(){
this.$store.dispatch("add", {
nName: this.$store.state.name,
nPrice: this.$store.state.price,
nSub: this.$store.state.sub,
nImg: this.$store.state.img,
nDate: this.$store.state.date,
});
}
}
}
</script>
you can find a working example here
https://codesandbox.io/s/vuex-store-forked-d8895
Related
I'm trying to make my form somehow more user-friendly. So don't show at the first spot all the fields but only the necessary one, and if a user will meet certain criteria, then show the rest of the fields. It's based on newest bootstrap. My codes are like below:
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation');
var showHidden = document.querySelectorAll('.d-none');
var selectGroup = document.getElementById('target-audience');
selectGroup.addEventListener('change', function handleChange(event) {
if (event.target.value === '8') {
showHidden.style.display = 'block!important';
} else {
showHidden.style.display = 'none';
}
});
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
#import url('https://fonts.googleapis.com/css2?family=Poppins:wght#400;700&display=swap');
html, body {
font-family: 'Poppins', sans-serif;
}
#mailchimp-container h1 {
font-size:1em;
text-transform:uppercase;
font-weight:bold;
}
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container" id="mailchimp-container">
<div class="row">
<div class="col">
<h1 class="py-3">
Form test
</h1>
<form class="needs-validation" novalidate>
<div class="form-group">
<label for="email" class="col-form-label">Email</label>
<input id="email" name="email" type="email" class="form-control" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="form-group">
<label for="fname" class="col-form-label">Name</label>
<input id="fname" name="fname" type="text" class="form-control" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="form-group">
<label for="target-audience" class="col-form-label">Who are you?</label>
<select id="target-audience" name="target-audience" class="form-select" required>
<option disabled selected value="">--</option>
<option value="8">Fans of cars, motors and bikes</option>
<option value="16">Fans of flowers</option>
<option value="24">Fans of food</option>
</select>
<div class="invalid-feedback">
Pick proper option
</div>
</div>
<div class="form-group">
<label for="location" class="col-form-label">Your location</label>
<select id="location" name="location" class="form-select" required>
<option disabled selected value="">--</option>
<option value="europe">Europe</option>
<option value="anz">ANZ</option>
<option value="americas">Americas</option>
</select>
<div class="invalid-feedback">
Pick proper option
</div>
</div>
<div class="form-group d-none">
<label for="fav-car" class="col-form-label">Favourite car brand</label>
<input id="fav-car" name="fav-car" type="text" class="form-control">
</div>
<div class="form-group d-none">
<label for="fav-bike" class="col-form-label">Favourite bike brand</label>
<input id="fav-bike" name="fav-bike" type="text" class="form-control">
</div>
<div class="form-group d-none">
<label for="fav-motorcycle" class="col-form-label text-start">Favourite motorcycle brand</label>
<input id="fav-motorcycle" name="fav-motorcycle" type="text" class="form-control">
</div>
<div class="form-group py-3">
<button name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
While the form is validating properly, unfortunately the javascript that is suppose to show the fields doesn't. In practice when a user will pick value=8 so he will be a fan of cars/bikes/motors, then the fields should appear.
Thank!
showHidden has a 3 nodes. So you need to iterate and for importing implementation you can use setProperty() method like this;
selectGroup.addEventListener('change', function handleChange(event) {
if (event.target.value === '8') {
showHidden.forEach(div => div.style.setProperty('display', 'block', 'important'))
} else {
showHidden.forEach(div => div.style.setProperty('display', 'none', 'important'))
}
});
Loop through showHidden since it's a NodeList, then use setAttribute('style', 'display: block!important') since you can't add important to an HTMLElement:
(function() {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation');
var showHidden = document.querySelectorAll('.d-none');
var selectGroup = document.getElementById('target-audience');
selectGroup.addEventListener('change', function(event) {
if (event.target.value === '8') {
showHidden.forEach(function(el) {
el.setAttribute('style', 'display: block!important');
})
} else {
showHidden.forEach(function(el) {
el.setAttribute('style', 'display: none');
})
}
});
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function(form) {
form.addEventListener('submit', function(event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
#import url('https://fonts.googleapis.com/css2?family=Poppins:wght#400;700&display=swap');
html,
body {
font-family: 'Poppins', sans-serif;
}
#mailchimp-container h1 {
font-size: 1em;
text-transform: uppercase;
font-weight: bold;
}
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="container" id="mailchimp-container">
<div class="row">
<div class="col">
<h1 class="py-3">
Form test
</h1>
<form class="needs-validation" novalidate>
<div class="form-group">
<label for="email" class="col-form-label">Email</label>
<input id="email" name="email" type="email" class="form-control" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="form-group">
<label for="fname" class="col-form-label">Name</label>
<input id="fname" name="fname" type="text" class="form-control" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="form-group">
<label for="target-audience" class="col-form-label">Who are you?</label>
<select id="target-audience" name="target-audience" class="form-select" required>
<option disabled selected value="">--</option>
<option value="8">Fans of cars, motors and bikes</option>
<option value="16">Fans of flowers</option>
<option value="24">Fans of food</option>
</select>
<div class="invalid-feedback">
Pick proper option
</div>
</div>
<div class="form-group">
<label for="location" class="col-form-label">Your location</label>
<select id="location" name="location" class="form-select" required>
<option disabled selected value="">--</option>
<option value="europe">Europe</option>
<option value="anz">ANZ</option>
<option value="americas">Americas</option>
</select>
<div class="invalid-feedback">
Pick proper option
</div>
</div>
<div class="form-group d-none">
<label for="fav-car" class="col-form-label">Favourite car brand</label>
<input id="fav-car" name="fav-car" type="text" class="form-control">
</div>
<div class="form-group d-none">
<label for="fav-bike" class="col-form-label">Favourite bike brand</label>
<input id="fav-bike" name="fav-bike" type="text" class="form-control">
</div>
<div class="form-group d-none">
<label for="fav-motorcycle" class="col-form-label text-start">Favourite motorcycle brand</label>
<input id="fav-motorcycle" name="fav-motorcycle" type="text" class="form-control">
</div>
<div class="form-group py-3">
<button name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
There is a form on angular 8
my-form.component.html
<div class="container">
<form novalidate [formGroup]="registrationForm">
<div class="form-group">
<label for="firstName">Имя:</label>
<input #spy required pattern=[A-Za-zА-Яа-яЁё]{2,} name="firstName" id="firstName" type="text" class="form-control" formControlName="firstName">
</div>
<div class="form-group">
<label for="lastName">Фамилия:</label>
<input #spy required pattern=[A-Za-zА-Яа-яЁё]{2,} name="lastName" id="lastName" type="text" class="form-control" formControlName="lastName">
</div>
<div class="form-group">
<label for="email">E-mail:</label>
<input #spy required email name="email" id="email" type="email" class="form-control" formControlName="email">
</div>
<!--{{ spy.className }}-->
<button type="submit" class="btn btn-succes" (click)="submit(myForm)">Отправить</button>
</form>
When the user writes data, the submit button should send data to the API using the POST method.
If you need any code, leave a comment
ts code:
import { FormGroup, FormControl } from '#angular/forms';
import {HttpClient} from '#angular/common/http';
#Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {
registrationForm: FormGroup;
constructor() { }
ngOnInit() {
this.registrationForm = new FormGroup({
firstName: new FormControl(),
lastName: new FormControl(),
email: new FormControl()
});
}
}```
i have simple example for you....
reference
----html----
<header class="masthead">
<div class="container h-100">
<div class="row h-100 align-items-center justify-content-center">
<div class="col-6">
<div class="text-center">
<hello name="{{ name }}"></hello>
<hr>
</div>
<form #send="ngForm" (ngSubmit)="sendFRMData(send.value)">
<div class="form-group">
<label for="title" class="text-muted">Title</label>
<input type="text" class="form-control" id="title"
name="titlefrm" ngModel #title='ngModel' required>
<span class="help-block text-danger" *ngIf="!title.valid &&
title.touched">Please give Title!!</span>
</div>
<div class="form-group">
<label for="body" class="text-muted">Body</label>
<input type="text" class="form-control" id="body" name="bodyfrm" ngModel
#body='ngModel' required>
<span class="help-block text-danger" *ngIf="!body.valid &&
body.touched">Please
give Body!!</span>
</div>
<div class="form-group">
<label for="userId" class="text-muted">UserID</label>
<input type="text" class="form-control" id="userId" name="userIdfrm" ngModel
#userid='ngModel' required>
<span class="help-block text-danger" *ngIf="!userid.valid &&
userid.touched">Please give UserID!!</span>
</div>
<div class="row">
<div class="col-sm-6">
<input class="form-control btn btn-success" type="submit"
[disabled]='!send.valid'>
</div>
<div class="col-sm-6">
<input class="form-control btn btn-info" type="button" value="EDIT"
(click) = 'onEdit()'>
</div>
</div>
</form>
</div>
</div>
</div>
</header>
----ts----
import { NgForm } from '#angular/forms';
#ViewChild('send') send: NgForm;
constructor(private sendData: HttpService) {
}
sendFRMData(data: any) {
const payload = {
title: data.titlefrm,
body: data.bodyfrm,
userId: data.userIdfrm
}
this.sendData.try(payload).subscribe(
(data: any) => {
this.respondedData = JSON.stringify(data);
this.alert = true;
}
);
}
----service----
try(data){
return
this.http.post('https://jsonplaceholder.typicode.com/posts',data,{
headers: {
"Content-type": "application/json; charset=UTF-8"
}
});
}
hope you get your answer...
Seems like you are not able to get form values in your submit function.
change your click event from (click)="submit(myForm)" to (click)="submit(myForm.value)" then in your submit function you can call post method
submit(formValueObject) {
console.log(formValueObject);
this.httpService.post(url, formValueObject).subscribe((res:any)=> {
//your response
})
}
I hope it helps
Trying to collect all the HTML data from my form, then to store it as an object and then send it using ajax request. Any ideas, please? Appreciate some help. I was trying with serialize's jquery, but read this in that way cannot be sent (to an API URL, no PHP) using ajax(post).
<form class="form" action="" method="" id="createProposal">
<div class="form-group">
<label class="col-md-12 control-label" for="asset-drop">Asset</label>
<div class="col-md-12">
<select id="asset-drop" name="asset-drop" class="form-control" >
<option value="1"> {{ this.assets[0] ? this.assets[0].name : '' }} </option>
<option value="2">{{ this.assets[1] ? this.assets[1].name : '' }}</option>
<option value="3">{{ this.assets[2] ? this.assets[2].name : '' }}</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-12 control-label" for="amount-invest">Amount</label>
<div class="col-md-12">
<input id="amount-invest" name="amount-invest" type="text" placeholder="Currency" class="form-control input-md">
</div>
</div>
<div class="form-group">
<label class="col-md-12 control-label" for="description-input">Description</label>
<div class="col-md-12">
<textarea class="form-control" id="description-input" name="description-input"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary cancel" v-on:click="hideCreatePropolsal">Cancel</button>
<button type="submit" class="btn btn-primary create" v-on:click="formDataCreation">Create</button>
</div>
</form>
i suggest to create an object in your data section which you call proposal and bind your form to that object using v-model, i'm using single file component but it doesn't matter, you can fit that solution to your case :
<template>
<form class="form" action="" method="" id="createProposal">
<div class="form-group">
<label class="col-md-12 control-label" for="asset-drop">Asset</label>
<div class="col-md-12">
<select id="asset-drop" name="asset-drop" class="form-control" v-model="proposal.selectedAsset" >
<option :value="index" :key="index" v-for="(asset,index) in proposal.assets">{{asset}} </option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-12 control-label" for="amount-invest">Amount</label>
<div class="col-md-12">
<input id="amount-invest" v-model="proposal.amount" name="amount-invest" type="text" placeholder="Currency" class="form-control input-md">
</div>
</div>
<div class="form-group">
<label class="col-md-12 control-label" for="description-input">Description</label>
<div class="col-md-12">
<textarea class="form-control" v-model="proposal.description" id="description-input" name="description-input"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary cancel" v-on:click="hideCreatePropolsal">Cancel</button>
<button type="submit" class="btn btn-primary create" v-on:click="formDataCreation">Create</button>
</div>
</form>
</template>
<script>
export default {
data(){
return{
proposal:{
assets:[],
selectedAsset:'',
amount:'',
description:''
}
}
},
methods:{
hideCreatePropolsal(){
},
formDataCreation(){
/* $.ajax({
url: "yourUrl",
type: "POST",
data:this.proposal,
success: function (response) {
}});*/
}
}
};
</script>
<style>
</style>
you could check the whole code
How to get auto increment Id?I created the database.It has customer registration form.Customer Id is auto-generated in DB.I want to fill Id input field by a max value of Id column.ex:
my source code(register.blade.php)
#extends('layerout.registration')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<form action="/insert" method="post">
<center><font color="white"><h2>Registration form</h2></font></center>
<div class="form-group">
{{csrf_field() }}
<script type="text/javascript">
<label for="example-number-input" class="col-2 col-form-label">ID</label>
<input class="form-control" type="number" value="1" name="id">
</script>
<label for="example-text-input" class="col-2 col-form-label">Name</label>
<input class="form-control" type="text" value="name" name="Name">
<label for="example-text-input" class="col-2 col-form-label">Job_titleID</label>
<select class="form-control" type="text" value="0" name="Job_ID"> <option>-0-</option>
#foreach($register as $cat)
<option value="{{$cat->Job_ID}}" name="Job_ID">{{$cat->Job_ID}}</option>
#endforeach
</select>
<label for="example-text-input" class="col-2 col-form-label">Identifier</label>
<input class="form-control" type="text" value="93xxxxxxV" name="Identifier">
<label for="example-text-input" class="col-2 col-form-label">Street</label>
<input class="form-control" type="text" value="Panagoda road" name="Road">
<label for="example-text-input" class="col-2 col-form-label">city</label>
<input class="form-control" type="text" value="Rakwana" name="City">
<label for="example-text-input" class="col-2 col-form-label">Postal Code</label>
<input class="form-control" type="text" value="7000" name="P_code">
<label for="example-text-input" class="col-2 col-form-label">Countery</label>
<input class="form-control" type="text" value="Sri Lanaka" name="Address">
<label for="example-email-input" class="col-2 col-form-label">Email</label>
<input class="form-control" type="email" value="mithika.hetti#gmail.com" name="email">
<label for="example-tel-input" class="col-2 col-form-label">Telephone</label>
<input class="form-control" type="tel" value="+94 071 172 6818" name="tel">
<label for="example-datetime-local-input" class="col-2 col-form-label">Date and time</label>
<input class="form-control" type="datetime-local" value="2011-08-19T13:45:00" name="datetime-local">
<br>
<br>
<button type="Submit" name="Submit" value="Add" id="add" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
#endsection
my controller
<?php namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Job_ID;
class register extends Controller{
public function register()
{
$register=Job_ID::all();
return view('cutomer.register',['register' => $register]);
}
function insert(Request $req)
{
$ID=$req->input('ID');
$Name=$req->input('Name');
$Job_ID=$req->input('Job_ID');
$Identifier=$req->input('Identifier');
$Road=$req->input('Road');
$City=$req->input('City');
$P_code=$req->input('P_code');
$Address=$req->input('Address');
$email=$req->input('email');
$tel=$req->input('tel');
$datetimelocal=$req->input('datetime-local');
$data = array('E_ID'=>$ID,"E_Name"=>$Name,"Job_ID"=>$Job_ID,"E_Phone"=>$Identifier,"Road" =>$Road,"City" =>$City,"P_Code" =>$P_code,"E_Address" =>$Address,"E_email"=>$email,"E_Phone" =>$tel,"Date"=>$datetimelocal);
DB::table('employer')->insert($data);
}
}
I created ID column and set auto increment it in Mysql.I want to display max value(4) on Id text-field of customer registration form.
with mysql you can do this
SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = "databaseName"
AND TABLE_NAME = "tableName"
for laravel
$table = DB::select("SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'databaseName' AND TABLE_NAME = 'tableName'");
if (!empty($table)) { echo $table[0]->AUTO_INCREMENT; }
If you are asking how to show the id of a Model, first in your controller, make a collection query like:
$posts= Post::all();
return view(view.post)->withPosts($posts);
and then on your blade file, make a foreach to iterate through all the posts:
#foreach ($postsas $post)
<p>This is ID number {{ $post->id }}</p>
#endforeach
If you are asking how to manually auto increment a certain column, this is the code I used to manually make an auto-increment column (form_counter) starting with value of 1. Basically, I check if there is an existing record, if there is none, the first record for the form_counter column is 1. If it is existing, add 1 to the most current value in the column.
$lastValueCollection = Post::where('formId', $request->inputFormId)->orderBy('Term', 'desc')->first();
$form_counter = 1;
if(isset($lastValueCollection->form_counter)){
$form_counter = $lastValueCollection->form_counter + 1;
}
$data = array('E_ID'=>$ID,....., 'Client_ID'=>$form_counter);
DB::table('employer')->insert($data);
This is not exact but I hope this gives you an idea.
on your schema builder: $table->increments('yourPrimaryKey');
example :
Schema::table('users', function (Blueprint $table) {
$table->increments('id');
});
See the the docs: https://laravel.com/docs/5.5/migrations
I am new to angular and am trying (and failing) to get the ngClass to work with some validation on a basic contact form.
I want to highlight the inputs when they are in the success/error by highlighting with bootstrap 'has-error' and 'glyphicon-remove' classes if there are any issues with the data.
my form is as follows;
<form class="row instant-quote-form" ng-controller="formCtrl" ng-cloak>
<div class="col-md-12">
<h2>Quick Form</h2>
<div class="form-group has-feedback">
<div class="input-group col-md-12">
<label for="titleSelect" class="input-group-addon">Title :</label>
<select name="titleSelect" id="titleSelect" class="form-control"
ng-model="form.titleResult" required>
<option value="">Select Title...</option>
<option ng-repeat="option in titles" value="{{option.name}}">{{option.name}}</option>
</select>
</div>
<div class="input-group col-md-12" ng-class="{ 'has-error': form.name.$invalid, 'text-success' : form.name.$valid}">
<label for="nameInput" class="input-group-addon">Name :</label>
<input type="text" class="form-control" id="nameInput" placeholder="Full Name..." ng-model="form.name" required>
<span ng-class="{ 'glyphicon-remove' : form.name.$invalid, 'glyphicon-ok' : form.name.$valid }" class="glyphicon form-control-feedback"></span>
</div>
<div class="input-group col-md-12">
<label for="postcodeInput" class="input-group-addon">Postcode :</label>
<input type="text" class="form-control" id="postcodeInput" placeholder="Postcode..." ng-model="form.postcode" required>
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="input-group col-md-12">
<label for="emailInput" class="input-group-addon">Email :</label>
<input type="email" class="form-control" id="emailInput" placeholder="Email Address..." ng-model="form.email" required>
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="input-group col-md-12">
<label for="telephoneInput" class="input-group-addon">Telephone :</label>
<input type="text" class="form-control" id="telephoneInput" placeholder="Telephone Number..." ng-model="form.telephone" required>
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="input-group col-md-12">
<label for="timeSelect" class="input-group-addon">To to Call :</label>
<select name="timeSelect" id="timeSelect" class="form-control"
ng-model="form.timeResult" required>
<option value="">Select Time...</option>
<option ng-repeat="option in times" value="{{option.name}}">{{option.name}}</option>
</select>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-primary btn-block" ng-click="submit(form)">Request Callback!</button>
</div>
</div>
</div>
</form>
my controller is as follows;
'use strict';
app.controller('formCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.titles =
[
{ id: '1', name: 'Mr.' },
{ id: '2', name: 'Mrs.' },
{ id: '3', name: 'Master.' },
{ id: '4', name: 'Miss.' },
{ id: '5', name: 'Sir.' },
{ id: '6', name: 'Dr.' },
{ id: '7', name: 'Other.' }
];
$scope.times =
[
{ id: '1', name: 'Morning.' },
{ id: '2', name: 'Afternoon.' }
];
$scope.submit = function (form) {
console.log(form);
};
}]);
However, the ngclass directive is not being applied? also it seems that the submit is being called even when the form is invalid? do I need to validate the form fromthe controller as well?
Add a name attribute and value to your form tag & input...
<form name="form" class="row instant-quote-form" ng-controller="formCtrl" ng-cloak>
&
<input name="name" type="text" class="form-control" id="nameInput" placeholder="Full Name..." ng-model="name" required>
because when you refer to form.name in 'has-error': form.name.$invalid it works based off of the name of the form and the name of the input box
Note there is a conflict using form.name as your ng-model based upon your controller you will want ng-model="name"
Here is a working plnkr