How to correctly validate a modal form - javascript

I can't seem to get validation to work on my bootstrap modal, I have struggled with several of the examples that I have encountered.
What is the correct way to validate a bootstrap modal?
My HTML:
<div class="modal fade" id="addMyModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Stuff</h4>
</div>
<div class="modal-body">
<form class="form-control" role="form" id="newModalForm">
<div class="form-group">
<label class="control-label col-md-3" for="email">A p Name:</label>
<div class="col-md-9">
<input type="text" class="form-control required error" id="pName" name="pName" placeholder="Enter a p name" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3" for="email">Action:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="action" placeholder="Enter and action">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="btnSaveIt">Save</button>
<button type="button" class="btn btn-default" id="btnCloseIt" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
My Javascript:
$(function () {
$("#newModalForm").validate({
rules: {
pName: {
required: true,
minlength: 8
},
action: "required"
},
messages: {
pName: {
required: "Please enter some data",
minlength: "Your data must be at least 8 characters"
},
action: "Please provide some data"
}
});
});
Based upon my code nothing appears to happen when I click the save button on modal. I am utilizing the jquery.validate.js script.
Can someone point me in the right direction?

You have two issues:
You're button needs to be set to type="submit" not type="button"
Your submit button should be inside your form tag.
See working example Snippet.
$(function() {
$("#newModalForm").validate({
rules: {
pName: {
required: true,
minlength: 8
},
action: "required"
},
messages: {
pName: {
required: "Please enter some data",
minlength: "Your data must be at least 8 characters"
},
action: "Please provide some data"
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#addMyModal">Open Modal</button>
<div class="modal fade" id="addMyModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Stuff</h4>
</div>
<div class="modal-body">
<form role="form" id="newModalForm">
<div class="form-group">
<label class="control-label col-md-3" for="email">A p Name:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="pName" name="pName" placeholder="Enter a p name" require/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3" for="email">Action:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="action" name="action" placeholder="Enter and action" require>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="btnSaveIt">Save</button>
<button type="button" class="btn btn-default" id="btnCloseIt" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>

If you need send data via AJAX from bootstrap modal use following code:
$("#addMyModal form").validate({
rules: {
Name: {
required: true,
minlength: 2
},
Email: {
required: true,
minlength: 5
},
Phone: {
required: true,
minlength: 12
}
},
messages: {
Name: {
required: "Обязательное поле",
minlength: "Минимальная длинна Имени 2 символа"
},
Email: {
required: "Обязательное поле",
minlength: "Минимальная длинна Email 5 символов",
email: "Пожалуйста введите корректный email адрес."
},
Phone: {
required: "Обязательное поле",
minlength: "Минимальная длинна Телефона 11 символов"
}
},
submitHandler: function(form) {
$.ajax({
url: './pay-vip.php',
type: 'POST',
data: $(form).serialize(),
success: function(response) {
location.replace(location + "pay-vip.php");
alert("Send mail")
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#addMyModal">Open Modal</button>
<div class="modal fade" id="addMyModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Stuff</h4>
</div>
<div class="modal-body">
<form role="form" id="newModalForm">
<div class="form-group">
<label class="control-label col-md-3" for="email">A p Name:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="pName" name="pName" placeholder="Enter a p name" require/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3" for="email">Action:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="action" name="action" placeholder="Enter and action" require>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="btnSaveIt">Save</button>
<button type="button" class="btn btn-default" id="btnCloseIt" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>

I had some similar problem. But it turned out that
$("#newModalForm").validate({ ... });
has to be put outside the
$(function () { });
This fixed my issue

Related

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

how to output field is required in the input form

i want to output "field is required " or minlength error messages inside input box or placeholder with box color becoming red via jQuery . i have my form and validations work but message goes out underneath the boxes which looks ugly and make some disorder in the form .
my code :
<form action="" method="POST" id="login_form">
<div class="form-group has-feedback">
<input type="username" name="username" id="username" class="form-control" placeholder="username" ><span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" name="password" id= "password" class="form-control" placeholder="Password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat"name="login">Sign In</button>
</div>
<!-- /.col -->
</div>
</form>
jQuery code :
<script type="text/javascript" src="http://code.jquery.com/jquery-3.2.1.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('form').validate({
rules: {
username: {
required: true,
minlength: 5
},
password: {
required: true,
minlength: 5
},
},
});
});
</script>
You can define your css for the .error class then detect on onkeyup for the input.error for removing the error label see code snippet :
$(document).ready(function() {
$('form').validate({
rules: {
username: {
required: true,
minlength: 5
},
password: {
required: true,
minlength: 5
},
},
});
$(document).on("keyup", "input.error", function(){
$("label[for='"+$(this).attr('id')+"']").hide();
});
});
.form-group {
position:relative;
}
label.error{
position:absolute;
top:0px;
left:0px;
background-color:#fff;
color:red;
}
input.error{
border:1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.js"></script>
<form action="" method="POST" id="login_form">
<div class="form-group has-feedback">
<input type="username" name="username" id="username" class="form-control" placeholder="username" ><span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" name="password" id= "password" class="form-control" placeholder="Password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat"name="login">Sign In</button>
</div>
<!-- /.col -->
</div>
</form>

Modal Dialog Validation ASP.NET/bootstrap

I've been trying to validate some control in a modal dialog for days now, and despite all the examples and other posts here on SO I can't seem to get it working...
In my webpage I have a button that opens a modal dialog. That modal dialog has three required input boxes: one for text and two for positive numeric values. I want to validate the inputs when the user clicks save using the fancy bootstrap feedback scheme like these examples:
http://formvalidation.io/examples/modal/
http://1000hz.github.io/bootstrap-validator/
If the input is valid then I'll take the values and process accordingly. I haven't gotten this far though. The modal does open currently.
I know these examples use forms, but since I'm using a master page, a nested form in my content page isn't allowed. So how can I validate the input and apply the feedback style to the invalid controls when the user clicks save?
<!-- Button to trigger modal -->
<button type="button" id="btnOpenModal" class="btn btn-info" data-toggle="modal" data-target="#myModal">Add</button>
<!-- Bootstrap Modal Dialog -->
<div class="modal fade" id="myModal" data-toggle="validator" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<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">Here is the modal dialog</h4>
</div>
<div id="loginForm" class="modal-body form-horizontal">
<h5>Describe what to do here...</h5>
<div class="form-inline form-group">
<label for="mdltxtId" class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="mdltxtId" name="mdltxtId" placeholder="item description" />
</div>
</div>
<div class="form-inline form-group">
<label for="mdltxtWgt" class="col-sm-3 control-label">Weight (LB)</label>
<div class="col-sm-9">
<input type="text" pattern="^[0-9]{1,}" title="Positive number only" class="form-control" id="mdltxtWeight" name="mdltxtWeight" placeholder="weight in pounds" />
</div>
</div>
<div class="form-inline form-group">
<label for="mdltxtLength" class="col-sm-3 control-label">Length (IN)</label>
<div class="col-sm-9">
<input type="text" pattern="^[0-9]{1,}" title="Positive number only" class="form-control" id="mdltxtLength" name="mdltxtLength" placeholder="length in inches" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<asp:Button ID="btnSave" runat="server" Text="Save" CssClass="btn btn-primary" />
<%--<button type="submit" class="btn btn-primary">Save changes</button>--%>
</div>
</div>
</div>
</div>
I probably could change the project to not use a master page to make life easier with forms - it's not required (default Web Forms project in VS2015 sets this up automatically).
Just to add...I'm primarily a VB.NET winforms developer so I'm probably missing a lot of fundamentals on ASP.NET and javascript so go easy on me.
Using the Bootstrap Validate plugin, you cannot validate input elements that are outside of a <form></form>. There is no workaround for this limitation.
with a Form id="Form"
<form id="Form">
<div class="modal-body form-horizontal">
<h5>Describe what to do here...</h5>
<div class="form-inline form-group">
<label for="mdltxtId" class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="mdltxtId" name="mdltxtId" placeholder="item description" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<asp:Button ID="btnSave" runat="server" Text="Save" CssClass="btn btn-primary" />
<%--<button type="submit" class="btn btn-primary">Save changes</button>--%>
</div>
</form>
Fiddle with Form
When form id="Form" changed into a div id="Form" and now the same code cannot be validate by Bootstrap Validate plugin. The plugin does nothing without a <form></form>.
<div id="Form" class="modal-body form-horizontal">
<h5>Describe what to do here...</h5>
<div class="form-inline form-group">
<label for="mdltxtId" class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="mdltxtId" name="mdltxtId" placeholder="item description" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<asp:Button ID="btnSave" runat="server" Text="Save" CssClass="btn btn-primary" />
<%--<button type="submit" class="btn btn-primary">Save changes</button>--%>
</div>
Fiddle with Div
So as Shehary pointed out the Bootstrap Validate plugin won't work on a modal dialog that is not a form. So to emulate the same effect, I added a span tag to each input to provide the feedback text and use javascript to to the validating and add the feedback styles.
Here is the modal:
<div class="modal fade" id="myModal" data-toggle="validator" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<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">Here is the modal dialog</h4>
</div>
<div id="loginForm" class="modal-body form-horizontal">
<h5>Describe what to do here...</h5>
<div class="form-inline form-group">
<label for="mdltxtId" class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
<input type="text" pattern="^.{1,}" title="Item name required" class="form-control" id="mdltxtId" name="mdltxtId" placeholder="item description"/>
<span id="mdlIdHelper" class="help-block h6"></span>
</div>
</div>
<div class="form-inline form-group">
<label for="mdltxtWgt" class="col-sm-3 control-label">Weight (LB)</label>
<div class="col-sm-9">
<input type="text" pattern="^[+]?([.]\d+|\d+[.]?\d*)" title="Positive number only" class="form-control" id="mdltxtWeight" name="mdltxtWeight" placeholder="weight in pounds" />
<span id="mdlWgtHelper" class="help-block h6"></span>
</div>
</div>
<div class="form-inline form-group">
<label for="mdltxtArm" class="col-sm-3 control-label">Arm (IN)</label>
<div class="col-sm-9">
<input type="text" pattern="^[0-9]{1,}" title="Positive number only" class="form-control" id="mdltxtArm" name="mdltxtArm" placeholder="arm length in inches" />
<span id="mdlArmHelper" class="help-block h6"></span>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="btnmdlSave2" onclick="CloseModal(); return false;">Save</button>
</div>
</div>
</div>
</div>
And here is the javascript:
function OpenModal() {
//window.alert('opening modal');
ResetModal();
//window.alert('modal was reset');
$('#myModal').modal('show');
//window.alert('modal was opened');
}
function ResetModal() {
//window.alert('beginning modal reset');
var mdlId = $('#mdltxtId');
var mdlWgt = $('#mdltxtWeight');
var mdlArm = $('#mdltxtArm');
// reset the item description input group
mdlId.closest('.form-group').removeClass('has-error').removeClass('has-success');
mdlId.val('');
mdlIdHelper.innerHTML = "";
// reset the item weight input group
mdlWgt.closest('.form-group').removeClass('has-error').removeClass('has-success');
mdlWgt.val('');
mdlWgtHelper.innerHTML = "";
// reset the arm length input group
mdlArm.closest('.form-group').removeClass('has-error').removeClass('has-success');
mdlArm.val('');
mdlArmHelper.innerHTML = "";
//window.alert('finished modal reset');
}
function ValidateModal() {
var mdlId = $('#mdltxtId');
var mdlWgt = $('#mdltxtWeight');
var mdlArm = $('#mdltxtArm');
var val = true
// Check if the input is valid
if (!mdlId.val()) {
// Add errors highlight
mdlId.closest('.form-group').removeClass('has-success').addClass('has-error');
mdlIdHelper.innerHTML = "You must enter a description";
val = false
} else {
// Add success highlight
mdlId.closest('.form-group').removeClass('has-error').addClass('has-success');
mdlIdHelper.innerHTML = "";
}
// Check if the input is valid
if (!mdlWgt.val() || !$.isNumeric(mdlWgt.val()) || mdlWgt.val() <= 0) {
// Add errors highlight
mdlWgt.closest('.form-group').removeClass('has-success').addClass('has-error');
mdlWgtHelper.innerHTML = "Item weight must be a positive numeric value";
val = false;
} else {
// Add success highlight
mdlWgt.closest('.form-group').removeClass('has-error').addClass('has-success');
mdlWgtHelper.innerHTML = "";
}
// Check if the input is valid
if (!mdlArm.val() || !$.isNumeric(mdlArm.val()) || mdlArm.val() <= 0) {
// Add errors highlight
mdlArm.closest('.form-group').removeClass('has-success').addClass('has-error');
mdlArmHelper.innerHTML = "Arm length must be a positive numeric value";
val = false;
} else {
// Add success highlight
mdlArm.closest('.form-group').removeClass('has-error').addClass('has-success');
mdlArmHelper.innerHTML = "";
}
// return false if there was an error in the modal dialog. A FALSE return value will prevent a postback to the server. Might be redundant since the button onclick also has 'return false'.
return val;
}
I faced the same problem, probably it's too late but here is the code I did. It's useful if you don't care about use ajax and json...
<!-- Modal -->
<div class="modal fade" id="modalOption" tabindex="-1" role="dialog" aria-labelledby="modalOptionLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<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="modalOptionLabel">Options</h4>
</div>
<div class="modal-body">
#using (Html.BeginForm("Save", "Option", FormMethod.Post, new { id = "frmTest" }))
{
Html.AntiForgeryToken();
<div class="row">
<div class="col-md-6">
<div class="col-md-6">
#Html.LabelFor(model => model.VALUE1)
#Html.TextBoxFor(model => model.VALUE1, String.Format("{0:#0.00}", Model.VALUE1), new { #class = "form-control input-decimal" })
#Html.ValidationMessageFor(model => model.VALUE1, "", new { #class = "label label-danger" })
</div>
</div>
<div class="col-md-6">
<div class="col-md-6">
#Html.LabelFor(model => model.VALUE2)
#Html.TextBoxFor(model => model.VALUE2, String.Format("{0:#0.00}", Model.VALUE2), new { #class = "form-control input-decimal" })
#Html.ValidationMessageFor(model => model.VALUE2, "", new { #class = "label label-danger" })
</div>
</div>
</div>
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-sm" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary btn-sm crud-save" id="SaveOption" data-target="#modalOption" data-container="#divOptionGrid" form="frmTest">Save</button>
</div>
</div>
</div>
</div>
<script>
$(document).off('click', '.crud-save').on('click', '.crud-save', function (event) {
var formName = $(this).attr("form");
var form = $("#" + formName)
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);
var isValid = $(form).validate().form();
if (!isValid) {
event.preventDefault();
return false;
}
var formInfo = form.serialize();
//here goes your ajax implementation
$.ajax({
type: form.attr('method'),
dataType: "json",//response by using json
url: form.attr('action'),
data: formInfo,
success: function (customJson) //just return a JsonResult from the controller if the process is successful
{
if(customJson.isDone){
alert("Done");
$("#modalOption").modal('hide');
}
else{
alert(customJson.errorMessage);
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
}
});
</script>

Krajee Bootstrap File Input unresponsive

I'm trying to use this plugin and I'm not getting anything back when I click submit on the form.
This is the form that is inside a modal. I'm using bootstrap.
<form id="myForm" action="#" method="post" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true" id="closeModalTimes">
×
</button>
<h4 class="modal-title">Upload New Document</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Name *</label>
<input class="form-control" type="text" id="name" name="name" required />
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Subject *</label>
<textarea name="subject" id="subject" class="form-control" required></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="inputFile">Document File *</label>
<input type="file" name="inputFile" id="inputFile" required>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn" id="closeModalButton">
Close
</button>
<button type='button' id="submitFile" class='btn'>
Send
</button>
</div>
</div><!-- /.modal-content -->
<input name="myId" type="hidden" id="myId" value="393839334034933">
<input name="user" type="hidden" id="user" value="339">
<input name="page" type="hidden" id="page" value="test">
</form>
This is the jquery on the bottom of the page
$("#inputFile").fileinput({
overwriteInitial: false,
maxFileSize: 4000,
showPreview: false,
showUpload: false,
uploadAsync: true,
allowedFileExtensions: ["jpg", "jpeg", "gif", "png"],
browseClass: "btn btn-info",
elErrorContainer: "#documentErrorBlock",
msgSizeTooLarge: "File exceeds size",
msgInvalidFileExtension: "Invalid extension",
uploadURL: "upload.php",
uploadExtraData: function() {
return {
id: $("#myId").val(),
userId: $("#user").val(),
page: $("#page").val(),
name: $("#name").val(),
subject: $("#subject").val()
};
}
});
$('#inputFile').on('filebatchuploadsuccess', function(event, data, previewId, index) {
alert('success: '+data.response);
});
$('#inputFile').on('filebatchuploaderror', function(event, data, previewId, index) {
alert('error: '+data.response);
});
$("#submitFile").click(function(e) {
$('#inputFile').fileinput('upload');
});
And this is the PHP file:
$output = array();
$output['message'] = 'Reached PHP';
$output['success'] = true;
echo json_encode($output);
When I click nothing happens at all... not an error message or anything...
Thanks for your help!
The reason for not submitting came from your "uploadURL" which is spelt wrongly according to the documentation.
Change this
uploadURL: "upload.php",
to
uploadUrl: "upload.php",
that solves your problem.
http://plugins.krajee.com/file-input#option-uploadurl

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