Why form serialize does not work in this case? - javascript

I have a form which I wanna send via AJAX so I'll use serialize jQuery function.
This is the code (not all the elements has "name", but anyway the alert should display something):
http://jsfiddle.net/T6Rz3/2/
JS
$('#add-producto').click(function (e) {
alert($('#datos-add').serialize())
$.ajax({
type: "POST",
url: "insertar.php",
data: $('#datos-add').serialize(),
success: function (data) {
alert(data);
}
});
e.preventDefault();
});
HTML
<form id="#datos-add">
<div class="form-horizontal">
<div class="modal modal-block">
<div class="modal-header">
<h3>Añadir productos</h3>
</div>
<div class="modal-body">
<div class="control-group">
<label class="control-label">Marca</label>
<div class="controls">
<input type="text" name="marca" id="marca" class="input-xlarge">
</div>
</div>
<div class="control-group">
<label class="control-label">Producto</label>
<div class="controls">
<input type="text" name="descr" id="descr" class="input-xlarge">
</div>
</div>
<div class="control-group">
<label class="control-label">Tallajes</label>
<div class="controls controls-row">
<input id="tallajes" value="España">
</div>
</div>
<div class="control-group">
<label class="control-label">Referencias</label>
<div class="controls controls-row">
<input id="referencias" class="input-xlarge">
</div>
</div>
<div class="control-group">
<label class="control-label">Número de tallas</label>
<div class="controls controls-row">
<input type="number" min="1" max="99" value="5" id="numero-tallas" class="span1">
</div>
</div>
<div class="control-group">
<label class="control-label">Primera talla</label>
<div class="controls controls-row">
<input type="text" id="primera-talla" value="XS" class="span1">
</div>
</div>
</div>
<div class="modal-footer">
<div class="btn-group">
<button id="borrar" class="btn" type="button">Borrar todo</button>
<button id="generar" class="btn btn-primary" type="button">Generar tabla</button>
</div>
</div>
</div>
<div class="form-horizontal">
<div id="formulario-medidas" class="modal modal-block">
<div class="modal-header">
<h4>Tabla de medidas</h4>
</div>
<div class="modal-body">
<table id="tabla-medidas" class="table table-bordered"></table>
</div>
<div class="modal-footer">
<button id="medidas-completadas" class="btn btn-success" type="button">Medidas completadas</button>
</div>
</div>
<div id="formulario-tallajes" class="modal modal-block">
<div class="modal-header">
<h4>Tabla de tallajes</h4>
</div>
<div class="modal-body">
<table id="tabla-tallajes" class="table table-bordered"></table>
</div>
<div class="modal-footer">
<button id="add-producto" class="btn btn-block btn-large btn-danger" type="button">Añadir producto</button>
</div>
</div>
</div>
</div>
</form>
Do you see what I'm doing wrong?
Any tip, advide or help will be appreciated, and if you need more info, let me know and I'll edit the post.

Your form id is "datos-añadir" but your JavaScript refers to "datos-add".
Here is a jsfiddle fork that works. All I did was fix the reference:
$('#add-producto').click(function (e) {
var $form = $('#datos-añadir');
alert($form.serialize());
return false;

Fist of all, there is a typo. It should be <form id="datos-add"> instead of <form id="#datos-add">.
But I also think you are serializing it the wrong way.
When you do a POST ajax call, you shoud use .serializeArray(), instead of .serialize().
The .serialize() will join all key/values like a query string.
The .serializeArray() will include all key/values in the request.
In short, try:
$('#add-producto').click(function (e) {
$.ajax({
type: "POST",
url: "insertar.php",
data: $('#datos-add').serializeArray(),
success: function (data) {
alert(data);
}
});
e.preventDefault();
});

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";
}

Displaying Javascript response object in MODAL

I have created a view as:
<div class="container" style="padding-top:20px">
<div class="row">
#foreach (var item in Model)
{
<div class="col-lg-4" style="padding-top:20px;">
<div class="card" style="width:18rem">
<img src="#Url.Content(item.ImagePath)" class="card-img-top" />
<div class="card-body">
<div class="row">
<h5 class="card-title">#item.ProductName</h5>
<p style="color:crimson">  ( Rs #item.ProductPrice )</p>
</div>
#*Details*#
<button class="btn btn-primary btndetails" data-product-id="#item.Id" #*data-target="#loginModal" data-toggle="modal"*#>Details</button>
</div>
</div>
</div>
}
</div>
when I click the Details button the JavaScript function is invoked in which I am making an ajax call to Admin controller and GetProduct actionMethod which takes an Id, Gets the data with that id and returns a JSON object:
<script>
$(document).ready(function () {
$(".btndetails").on("click", function () {
$.ajax({
method: "POST",
url: "/Admin/GetProduct/" + $(this).attr("data-product-id"),
success: function (response) {
}
});
});
});
</script>
Its all working correct until here, I get the object in success function response object but now I want to display that object in a MODAL that I have created as:
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="modal fade" data-backdrop="static" id="loginModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"> Details</h4>
<button class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
#using (Html.BeginForm())
{
}
</div>
<div class="modal-footer">
<button class="btn btn-success">Save</button>
<button class="btn btn-primary" data-dismiss="modal">Close</button>
<button class="btn btn-danger">Delete</button>
</div>
</div>
</div>
</div>
</div>
So in short I want to display the object I received in JavaScript Response object in MODAL I created.
Wait it looks like you are trying to use ASP.Net rendering engine (which is generated during request on SERVER side) to render a result of an AJAX request which is performed by the client.
Sorry friend but that's just not going to work.
I mean if you really have to use ASP.Net to render that form, I'd suggest creating a separate view which just returns the form (Html.BeginForm()) section, then use jquery to paste that into the modal-body class as a raw html.
$('.modal-body').html(response);
It'd be a really bad solution from a MVC point of view and I'd advise against that, but it'd get the job done.
I am succesful in woring out the solution as :
I used getElementById and value functions to get the MODAL input field and then used value function to set the values in response object to MODAL input fields.
My AJAX Call is :
$(".btndetails").on("click", function () {
$.ajax({
method: "POST",
url: "/Admin/GetProduct/" + $(this).attr("data-product-id"),
success: function (response) {
var pName = document.getElementById("pName");
pName.value = response.ProductName;
var pPrice = document.getElementById("pPrice");
pPrice.value = response.ProductPrice;
var pDPrice = document.getElementById("pDPrice");
pDPrice.value = response.DiscountPrice;
var imgTitle = document.getElementById("imgTitle");
imgTitle.value = response.ImageTitle;
var stock = document.getElementById("stock");
stock.value = response.Stock;
var description = document.getElementById("description");
description.value = response.Description;
var img = document.getElementById("img");
img.value = response.ImagePath;
$("#img").attr("src", img);
}
});
});
And the modal i created below it is :
<div class="modal-body">
<form>
<div class="row">
<div class="form-group">
<label for="exampleInputEmail1">Product Name</label>
<input id="pName" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div>
<img src="" id="img" width="150px" height="150px" style="float:right" />
</div>
</div>
<div class="row">
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Product Price</label>
<input id="pPrice" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Discount Price</label>
<input id="pDPrice" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
</div>
<div class="row">
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Image Title</label>
<input id="imgTitle" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Quantity in stock</label>
<input id="stock" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
</div>
<div class="row">
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Description</label>
<input id="description" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group col-lg-6">
<div class="col-lg-6">
<label for="exampleInputEmail1">Category</label>
#Html.DropDownList("Category", new SelectList((System.Collections.IEnumerable)ViewData["Category"], "Id", "CategoryName"), new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
</div>
</form>
</div>
Anfinal outpur is like :

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
});
};

JQuery .click function only works after second click if I close a modal

i have a page where I have two buttons, one that opens a modal, and another one that only submits.
I have a .click event on the second button. If i go on the page and click the second button the click event goes fine, BUT if i first open the modal, close it and then i hit the second button, the first time does nothing and the second time it fires the .click event.
I would like to always fire the click event.
this is my code
$(document).ready(function(){
var focusout = false;
$(".prueba").click(function () {
if (focusout == false) {
focusout = true;
return;
}
});
var validator =$('#form1').validate(
{
ignore: "",
rules: {
parametros: {
required: function() { return focusout == true; },
},
terminos: {
required: function() { return focusout == true; },
}
},
highlight: function(element) {
$(element).closest('.grupo').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.grupo').removeClass('has-error');
}
});
$(".cancel").click(function() {
validator.resetForm();
});
}); // end document.ready
button 1:
<button type="submit" class="btn btn-primary" name="nueva_articulo"><i class="icon-plus"></i> Nuevo Item</button>
button 2:
<button type="submit" class="btn btn-primary prueba" name="buscar">Buscar</button>
full form:
<form action="" method="post" id="form1" enctype="multipart/form-data">
<p>
<button type="submit" class="btn btn-primary" name="nueva_articulo"><i class="icon-plus"></i> Nuevo Item</button>
<button type="submit" class="btn btn-primary" name="carga_masiva"><i class="icon-arrow-up"></i> Carga Masiva</button>
</p>
<br>
<div class="col-lg-1 grupo">
</div>
<div class="col-lg-10 grupo">
<div class="panel panel-default pagination-centered">
<div class="panel-heading">Búsqueda en Catálogo</div>
<div class="panel-body">
<div class="form-group ">
<div class="col-lg-6 grupo">
<input type="text" class="form-control " id="terminos" name="terminos" placeholder="Términos de búsqueda">
</div>
<div class="col-lg-6 grupo">
<select id="e1" name="parametros" style=" width:80%">
<option></option>
<option value="1" >Autor</option>
<option value="2" >Título</option>
</select>
</div>
</div>
<br> <br>
<div style="text-align:center">
<button type="submit" class="btn btn-primary prueba" name="buscar">Buscar</button>
</div>
</div>
</div>
</div>
<div class="col-lg-1 grupo">
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" name="myModal" data-backdrop="static" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-wide">
<div class="modal-content">
<div class="modal-header">
<button type="submit" class="close cancel" data-dismiss="modal" aria-hidden="true">×</button>
{if isset($smarty.post.nueva_articulo) }
<h4 class="modal-title">Nueva Articulo</h4>
{/if} </div>
<div class="modal-body">
{if isset($smarty.post.nueva_articulo) }
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="art_titulo" class="control-label">Título</label>
<input type="text" class="form-control input-sm" name="art_titulo">
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="art_enlace" class="control-label">Enlace</label>
<input type="text" class="form-control input-sm" name="art_enlace">
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="aut_id" class="control-label">Autor(es)</label>
<input type='hidden' id='e13' name="autores" style='width:100%'/>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="art_contenido" class="control-label">Contenido</label>
<textarea class="form-control input-sm" name="art_contenido" rows="5" ></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="etiquetas" class="control-label">Etiquetas</label>
<input type="text" id="e12" name="etiquetas" style="width:100%">
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="foto" class="control-label">Imagen</label>
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Buscar… <input type="file" name="foto">
</span>
</span>
<input type="text" class="form-control" name="nombre" readonly="">
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<div class="checkbox">
<label>
<input type="checkbox" name="rating" value="si"> Habilitar Rating y Reviews
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="redes" value="si"> Habilitar Compatir en Redes Sociales
</label>
</div>
</div>
</div>
{/if}
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default cancel" data-dismiss="modal" name="cerrar">Cerrar</button>
{if isset($smarty.post.nueva_articulo) }
<button type="submit" class="btn btn-primary" name="insertar_articulo">Guardar Cambios</button>
{/if}
</div>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
<!-- /.modal -->
</form>
They are both of type submit. You should only have 1 submit button on a form
Button 1 could just be a button
<button class="btn btn-primary" name="nueva_articulo"><i class="icon-plus"></i> Nuevo Item</button>
If you want, you can create a Form Object in javascript and generate it dynamically. That will do that you don't need to depend of the submit and forms, just fill the form object with the inputs that you want programatically (that even accept files or images).
But anyway, it seems that you have more than one click events on the same button if the one you want is triggering at the second attempt. You could try to play with event.preventDefault or $.unbind.
As you said taht you need to submit the inputs of the modal, try to place the content of the modal inside the tag and remove the submit type of one of the buttons.

Categories