angularjs not post my option list value to backend - javascript

i have a form as the following
<form method="POST" name="addItem" role="form" ng-submit="saveAdd()">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Create Item</h4>
</div>
<div class="modal-body">
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6">
<strong>Category : </strong>
<div class="form-group">
<select ng-model="form.cid" placeholder="Category" name="cid" class="form-control" required >
<option value="1">abc</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6">
<strong>Title : </strong>
<div class="form-group">
<input ng-model="form.title" type="text" placeholder="Name" name="title" class="form-control" required />
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6">
<strong>Description : </strong>
<div class="form-group" >
<textarea ng-model="form.description" class="form-control" required>
</textarea>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6">
<strong>Alias : </strong>
<div class="form-group" >
<textarea ng-model="form.item_alias" class="form-control" required>
</textarea>
</div>
</div>
</div>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" ng-disabled="addItem.$invalid" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
and the angluarjs function will pass the data to laravel backend.
$scope.saveAdd = function(){
dataFactory.httpRequest('items','POST',{},$scope.form).then(function(data) {
$scope.data.push(data);
$(".modal").modal("hide");
});
}
the laravel backend error:
a foreign key constraint fails (`laravel_ang`.`items`, CONSTRAINT
`items_cid_foreign` FOREIGN KEY (`cid`) REFERENCES `category` (`id`)) (SQL:
insert into `items` (`title`, `description`, `item_alias`, `updated_at`,
`created_at`) values (test, 123, 23, 2016-11-12 09:41:35, 2016-11-12 09:41:35))
At laravel route, it is a resource controller:
Route::resource('items', 'ItemController');
In controller, the function:
public function store(Request $request)
{
$input = $request->all();
$create = Item::create($input);
return response($create);
}
Any ideas to include cid in insert statement?

Related

How to delete div and all element inside div? Javascript, html, css

I have a function that clears the entire div and it disappears but still appears in the inspect (html). This is a real problem because we have this input type field on the email and I got this empty data in email. I only want when this value is not chosen to completely remove me from html and inspect. Look at my code and try to catch the error. The most important things in the whole code that you need to pay attention are onchange="checkSelected()" in html and first script tag which manipulate with that. It should simply become a display none but it still stands there.
<div class="modal fade" id="montageModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content" style="display: flex;">
<div class="modal-body">
<form id="schedule_form" class="clearfix" action="index.php?route=api/reifenmontage" method="post">
<div class="container-fluid">
<div class="step_1" >
<h3 class="modal-title">Reifenmontage Termin buchen </h3>
<div class="row termin_row">
<div class="col-xs-12 col-sm-4">
<div class="row">
<label>Pneu-Typ</label>
</div>
</div>
<div class="col-xs-12 col-sm-6">
<div class="row">
<select onchange="checkSelected()" class="form-control" name="pneu" id="pneu">
<option value="Motorrad">Motorrad</option>
<option value="Auto">Auto</option>
</select>
</div>
</div>
</div>
<div id="additionalRow" class="row termin_row" >
<div id="reifenmontage-input" class="row termin_row">
<div class="col-xs-12 col-sm-4">
<div class="row">
<label>Mark und model</label>
</div>
</div>
<div class="col-xs-12 col-sm-4">
<div class="row">
<select name="marka" class="form-control" id="button-getdata">
</select>
</div>
</div>
<div class="col-xs-12 col-sm-4">
<div class="row">
<select name="model" class="form-control" id="result" >
</select>
</div>
</div>
</div>
</div>
<div class="row termin_row">
<div class="col-sm-4 col-xs-12">
<div class="row"><label>2. Terminvorschlag</label></div>
</div>
<div class="col-sm-4 col-xs-6">
<div class="row">
<div class="input-group date" id="date-2" data-termin="1">
<input type='text' class="form-control" name="date[1]" />
<span class="input-group-addon">um</span>
</div>
</div>
</div>
<div class="col-sm-4 col-xs-6">
<div class="row">
<div class="input-group time" id="time-2" data-termin="1">
<input type='text' class="form-control" name="time[1]" />
<span class="input-group-addon">Uhr</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="checkbox">
<label>
<input type="checkbox" name="accept" id="accept"> Ich akzeptiere die Teilnahmebedingungen
</label>
</div>
</div>
<div class="row text-center">
<button type="button" class="btn btn-primary btn-lg btn-submit" id="next_step" disabled="disabled">Anfrage senden</button>
</div>
</div>
<div class="step_2">
<h3 class="modal-title">Your contact info</h3>
<div class="">
<div class="form-group clearfix">
<input type="text" name="name" value="<?= $user['name'] ?>" placeholder="Name and Lastname" class="form-control name text" required />
</div>
<div class="form-group clearfix">
<input type="text" name="phone" value="<?= $user['phone'] ?>" placeholder="Phone" class="form-control phone text" required />
</div>
<div class="form-group clearfix">
<input type="email" name="email" value="<?= $user['email'] ?>" placeholder="Email" class="form-control email text" required />
</div>
<div class="text-center">
<button type="submit" id="submit" class="btn btn-default btn-lg btn-submit" >Suchen</button>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">SCHLIESSEN</button>
</div>
</div>
</div>
</div>
and my script tag
<script type="text/javascript">
let selectItem = document.getElementById('pneu');
let additionalRow = document.getElementById('additionalRow');
function checkSelected() {
if (selectItem.selectedIndex == "1") {
additionalRow.style.display = 'none';
} else {
additionalRow.style.display = 'block';
}
}
</script>
<script type="text/javascript">
$('#button-getdata').on('change', function() {
$.ajax({
url: 'index.php?route=api/reifenmontage/get_marka_data',
type: 'post',
data: $('#reifenmontage-input select'),
dataType: 'json',
beforeSend: function() {
},
success: function(json) {
if (json['success']) {
$("#result").empty();
for (i in json['success']) {
var element = json['success'][i];
var o = new Option(element['model'], element['model']);
$("#result").append(o);
html = "\t<option value=\""+ element['model'] + "\">" + element['model'] + "</option>\n";
$("#result").append(o);
}
// document.getElementById("schedule_form").reset();
}
}
});
});
</script>
<script type="text/javascript">
$.ajax({
url: 'index.php?route=api/reifenmontage/mark',
context: document.body,
success: function(data) {
const selectControl = $('#button-getdata');
selectControl.html(data.map(ExtractData).join(''));
}
});
function ExtractData(item) {
return ` <option value="${item.value}">${item.label}</option>`;
}
</script>
Try variant with detaching/attaching DOM elements
<script type="text/javascript">
let selectItem = document.getElementById('pneu');
//let additionalRow = document.getElementById('additionalRow');
let detached = '';
function checkSelected() {
if (selectItem.selectedIndex == "1") {
detached = $('#reifenmontage-input').detach();
} else {
detached.appendTo('#additionalRow');
}
}
</script>

Show a succes/error message if data was/wasn't stored in data base on the same form page

I have a form from where the user imput data to the database and a php file with the function to do so.
I'd like to show an alert message on the same form page using javascript without refresing the page.
I don't know much about JS and I have tried every possible solution I came across but I cannot find the solution yet, what am I doing wrong? I hope someone could help me.
Edit: I decided to use modals to do this but modal is not showing and PHP file gets opened
Edit 2: I got it to show the modal on screen, but It has no message, not even the title specified in the h4 tags
What I'd like the user to see as message is the echo in the PHP file.
this is what I tried:
form code:
<form role="form" id="frmUsuario">
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> ID Usuario:</label>
<input type="text" class="form-control" id="IDUsuario" name="txtIDUsuario" readonly>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> Nombre Comercial:</label>
<input type="text" class="form-control" id="NombreComercial" name="txtNombreComercial" required>
</div>
<div class="col-sm-6 form-group">
<label for="email"> Nombre del Representante:</label>
<input type="text" class="form-control" id="NombreRepresentante" name="txtNombreRepresentante" required>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Expediente:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Expediente" name="txtExpediente" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Observaciones:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Observaciones" name="txtObservaciones" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<button type="submit" name="btnEnviarUsuario" id="EnviarUsuario" class="btn btn-lg btn-default pull-right" >Enviar →</button>
</div>
<div class="col-sm-12 form-group">
</div>
</form>
Modal:
<!-- Modal -->
<div class="modal fade" id="ModalMSJ" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" style="font-weight: bold;" id="exampleModalLabel">Usuario</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="MSJ">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
JS function in the form page:
<script type="text/javascript">
$("#frmUsuario").submit(function(e){
e.preventDefault();
var btnEnvUsuario="EnviarUsuario"; //name
$.ajax({
type : 'POST',
data: $("#frmUsuario").serialize()+"&btnEnviarUsuario="+btnEnvUsuario,
url : 'Logica/Usuario.php',
success : function(data){
$("#MSJ").html(data);
$("#ModalMSJ").modal("show");
}
});
return false;
});
</script>
PHP file:
$IDUsuario=$_POST["txtIDUsuario"];
$NombreRepresentante=$_POST["txtNombreRepresentante"];
$NombreComercial=$_POST["txtNombreComercial"];
$Expediente=$_POST["txtExpediente"];
$Observacion=$_POST["txtObservaciones"];
if(isset($_POST["btnEnviarUsuario"]))
{
$Conexion = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($Conexion->connect_error)
{
die("Connection failed: " . $Conexion->connect_error);
}
$sql = "insert into usuario
(NombreRepresentante,NombreComercial,Expediente,Observacion)
values
('$NombreRepresentante','$NombreComercial','$Expediente','$Observacion');";
if($Conexion->query($sql) === TRUE) {
/*Message I'd like to show to user*/
echo "Usuario guardado exitosamente";
}
Just remove the form tag and it won't fully refresh the page.
Then remove your alert from the php file and put it as shown below
<script>
$(document).ready(function(){
$("#EnviarUsuario").click(function(){
$.ajax({
url: "Logica/Usuario.php",
type: 'post',
data: {"btnEnviarUsuario":document.getElementByName("EnviarUsuario").value},
success: function(result){
//You put here your alert
alert("Usuario guardado exitosamente");
}
});
});
});
</script>
seems you having problem for using bootstrap. I wrap it using jsfiddle and fake JSON API. You could try it. I Hope it help. It's just simple problem that you have there. , your code is wrong on the ajax data.
see this.
https://jsfiddle.net/hp9jzfmo/1/
$(function(){
$("#frmUsuario").submit(function(e){
e.preventDefault();
var btnEnvUsuario=$('#EnviarUsuario').val();
$.ajax({
type : 'POST',
data: $("#frmUsuario").serialize(), // This is the right one
url : 'https://jsonplaceholder.typicode.com/posts',
success : function(data){
$("#MSJ").html(JSON.stringify(data));
$("#ModalMSJ").modal('show');
}
});
return false;
});
});
the body should be
<form role="form" id="frmUsuario">
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> ID Usuario:</label>
<input type="text" class="form-control" id="IDUsuario" name="txtIDUsuario" readonly>
</div>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> Nombre Comercial:</label>
<input type="text" class="form-control" id="NombreComercial" name="txtNombreComercial" required>
</div>
<div class="col-sm-6 form-group">
<label for="email"> Nombre del Representante:</label>
<input type="text" class="form-control" id="NombreRepresentante" name="txtNombreRepresentante" required>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Expediente:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Expediente" name="txtExpediente" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Observaciones:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Observaciones" name="txtObservaciones" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<button type="submit" name="btnEnviarUsuario" id="EnviarUsuario" class="btn btn-lg btn-default pull-right" >Enviar →</button>
</div>
</div>
</form>
<!-- Modal -->
<div class="modal fade" id="ModalMSJ" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" style="font-weight: bold;" id="exampleModalLabel">Usuario</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="MSJ">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
The PHP Part I think you could do your self, as far as the data passed to server. I hope it helps :)
This is the final solution:
Form Code:
<form role="form" id="frmUsuario">
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> ID Usuario:</label>
<input type="text" class="form-control" id="IDUsuario" name="txtIDUsuario" readonly>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> Nombre Comercial:</label>
<input type="text" class="form-control" id="NombreComercial" name="txtNombreComercial" required>
</div>
<div class="col-sm-6 form-group">
<label for="email"> Nombre del Representante:</label>
<input type="text" class="form-control" id="NombreRepresentante" name="txtNombreRepresentante" required>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Expediente:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Expediente" name="txtExpediente" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Observaciones:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Observaciones" name="txtObservaciones" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<button type="submit" name="btnEnviarUsuario" id="EnviarUsuario" class="btn btn-lg btn-default pull-right" >Enviar →</button>
</div>
<div class="col-sm-12 form-group">
</div>
</form>
Modal Code
<div class="modal fade" id="ModalMSJ" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" style="font-weight: bold; color:black;" id="exampleModalLabel">Usuario</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" style="color:red;" id="MSJ">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS Code:
<script type="text/javascript">
$("#frmUsuario").submit(function(e){
e.preventDefault();
var btnEnvUsuario="EnviarUsuario"; //variable to check if user clicked the button
$.ajax({
type : 'POST',
data: $("#frmUsuario").serialize()+"&btnEnviarUsuario="+btnEnvUsuario,
url : 'Logica/Usuario.php',
success : function(data){
$("#MSJ").html(data);
$("#ModalMSJ").modal("show");
}
});
return false;
});
</script>
PHP File Code:
$IDUsuario=$_POST["txtIDUsuario"];
$NombreRepresentante=$_POST["txtNombreRepresentante"];
$NombreComercial=$_POST["txtNombreComercial"];
$Expediente=$_POST["txtExpediente"];
$Observacion=$_POST["txtObservaciones"];
if(isset($_POST["btnEnviarUsuario"]))
{
$Conexion = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($Conexion->connect_error)
{
die("Connection failed: " . $Conexion->connect_error);
}
$sql = "insert into usuario
(NombreRepresentante,NombreComercial,Expediente,Observacion)
values
('$NombreRepresentante','$NombreComercial','$Expediente','$Observacion');";
if($Conexion->query($sql) === TRUE) {
/*Message I'd like to show to user*/
echo "Usuario guardado exitosamente";
}

Collect data from form, stack in object and send it with AJAX using Vue

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

jquery validate in modal with meteorjs

I trying to use the jQuery validate in modal but this doesn't work or don't call the action to validate the inputs.
this is my from into the modal, this are into a template name="modalregistro"
<form id="formregister" class="p-t-15 formregister" role="form" method="get">
<div class="row">
<div class="col-sm-12">
<div class="form-group form-group-default">
<label>Correo electrónico</label>
<input type="text" name="uname" placeholder="usuario#correo.com" class="form-control" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group form-group-default">
<label>Contraseña</label>
<input type="password" id="setPassword" name="user[password]" placeholder="Minimo de 8 Carácteres" class="form-control" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group form-group-default">
<label>Validar contraseña</label>
<input type="password" name="user[password_confirmation]" placeholder="Minimo de 8 Carácteres" class="form-control" required>
</div>
</div>
</div>
<div class="row m-t-10">
<div class="col-md-6">
<p>Estoy de acuerdo con <strong>TP Landings</strong>, terminos y condiciones de uso y su Privacidad.</p>
</div>
<div class="col-md-6 text-right">
¿Ayuda? Contactar el soporte
</div>
</div>
<hr class="b-dashed b-grey">
<div class="row">
<div class="col-sm-6 col-xs-12">
<button data-dismiss="modal" class="btn btn-default btn-lg btn-large btn-block text-uppercase">Cancelar</button>
</div>
<div class="col-sm-6 col-xs-12">
<button id="btnHecho" class="text-uppercase btn btn-primary btn-lg btn-large btn-block btn-cons show-notification" type="submit">Crear cuenta</button>
</div>
</div>
</form>
I call this template into my Layout of the website
<template name="website">
<section class="website">
{{> navbarWebsite}}
</section>
{{> modallogin}}
{{> modalregistro}}
</template>
and this is my rendered
Template.website.rendered = function(){
$(function(){
$('.formregister').validate()
});
jQuery('.formregister').validate({
rules: {
"user[password]": {
minlength: 2
},
"user[password_confirmation]": {
minlength: 2,
equalTo : "#setPassword"
}
}
});
}
the jQuery validate are on, and the website.rendered too but I don't know why validate it.
You are calling the .validate() method twice on the same form...
$(function(){
$('.formregister').validate()
});
jQuery('.formregister').validate({
rules: { ...
.validate() is the initialization method and once called on a particular form, it cannot be called again. All subsequent calls will be ignored. Since your rules are declared from the second instance, they are ignored.
EDIT:
Perhaps you don't realize that you're using a class selector when your form only has an id.
The form only contains an id:
<form id="formregister" ...
But your selector is targeting class="formregister":
$('.formregister')
To select id="formregister", you'll need to use an id selector:
$('#formregister')

The angular controller shows the modal form is valid, when it's not

I have a form that's pops in a modal directive (bootstrap UI).
I have 2 input with html5 validation: "required".
In the controller I wanted to find out if the form is valid, then proceed to the server. After I ran into a problem with scopes (when I tried to reffer $scope.FormName.$valid), I found a solution by sending form name with the ng-click.
Then I saw that the controller code shows that the form is valid (even when the required field is empty).
How can I implement check if the form is valid before submitting it.
Here is my code:
form in html
<form name="EmailForm">
<div class="row">
<div class="col-md-1 lbl_hdr">
date:
</div>
<div class="col-md-1">
{{Curr_Date | date:'dd/MM/yyyy'}}
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-1">
</div>
</div>
<div class="row">
<div class="col-md-1 lbl_hdr">
from:
</div>
<div class="col-md-1">
<input type="email" required placeholder="email" />
<br />
<br />
</div>
</div>
<div class="row">
<div class="col-md-3 lbl_hdr">
message:
</div>
</div>
<div class="row">
<div class="col-md-1">
<textarea class="msg_text" required rows="5"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-9">
<button type="submit" ng-click="SendEmail(EmailForm)" class="btn btn-primary btn_padded_top">send</button>
<button type="button" class="btn btn-primary btn_padded_top pull-left" ng-click="$close();">cancel</button>
</div>
</div>
</div>
</div>
</form>
controller
$scope.openModal = function () {
var modalInstance = $modal.open({
templateUrl: '/js/app/templates/msg_modal.html',
controller: function ($scope) {
$scope.Curr_Date = new Date();
$scope.SendEmail = function (EmailForm) {
if (EmailForm.$valid) {
EmailService.sendEmail("sdsd").success(
function (data) {
});
}//if valid
};
},
size: size
});
};
"if (EmailForm.$valid)" = always true
I had the same problem and turns out that the form elements must have ng-model in order for the AngularJS validation to kick in.
So just add it to all elements and it should be all good, e.g.
<input type="email" required placeholder="email" ng-model="email" />
Try using ng-submit and sending EmailForm.$valid in the arguments.
<form name="EmailForm" ng-submit="SendEmail(EmailForm.$valid)">
<div class="row">
<div class="col-md-1 lbl_hdr">
date:
</div>
<div class="col-md-1">
{{Curr_Date | date:'dd/MM/yyyy'}}
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-1">
</div>
</div>
<div class="row">
<div class="col-md-1 lbl_hdr">
from:
</div>
<div class="col-md-1">
<input type="email" required placeholder="email" />
<br />
<br />
</div>
</div>
<div class="row">
<div class="col-md-3 lbl_hdr">
message:
</div>
</div>
<div class="row">
<div class="col-md-1">
<textarea class="msg_text" required rows="5"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-9">
<button type="submit" class="btn btn-primary btn_padded_top">send</button>
<button type="button" class="btn btn-primary btn_padded_top pull-left" ng-click="$close();">cancel</button>
</div>
</div>
</div>
</div>
</form>
Then:
$scope.openModal = function () {
var modalInstance = $modal.open({
templateUrl: '/js/app/templates/msg_modal.html',
controller: function ($scope) {
$scope.Curr_Date = new Date();
$scope.SendEmail = function (isValid) {
if (isValid) {
EmailService.sendEmail("sdsd").success(
function (data) {
});
}//if valid
};
},
size: size
});
};

Categories