Why JQuery validate.js is not working with Spring Form? - javascript

I am trying validation on adding select item using JQuery validate.js in spring form. but validation is happening for only one field and if I submit blank category is submitted. I don't know what is happening wrong here.
I added this jquery files
<!-- JQuery -->
<script src="${js}/jquery.js"></script>
<!-- validate js-->
<script src="${js}/jquery.validate.js"></script>
<!-- Bootstrap core JavaScript -->
<script src="${js}/bootstrap.min.js"></script>
This is my code where I used spring form.
form.jsp
<div class="modal fade" id="myCategoryModal" tabindex="-1"
role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add New Category</h5>
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!-- Category form -->
<sf:form id = "categoryForm" modelAttribute="category"
action="${contextRoot}/manage/category" method="POST" class="">
<div class="form-group row">
<label for="category_name" class="col-sm-4 col-form-label">Category
Name</label>
<div class="col-sm-8">
<sf:input type="text" path="name" class="form-control"
id="category_name" />
</div>
</div>
<div class="form-group row">
<label for="category_description" class="col-sm-4 col-form-label">Category
Description</label>
<div class="col-sm-8">
<sf:textarea type="text" cols="" rows="4" path="description"
class="form-control" id="category_description" />
</div>
</div>
<div class="form-group row">
<div class="offset-sm-4 col-sm-8">
<input type="submit" value="Add Category"
class="btn btn-primary" />
</div>
</div>
</sf:form>
</div>
</div>
</div>
</div>
customjs.js
// validation code for category
var $categoryForm = $('#categoryForm');
if ($categoryForm.length) {
$categoryForm
.validate({
rules : {
name : {
required : true,
minlength : 2
},
description : {
requried : true
}
},
messages : {
name : {
required : 'Please add the category name!',
minlength : 'The category name should not be less than 2 characters'
},
description : {
required : 'Please add a description for this category!'
}
},
errorElement : 'em',
errorPlacement : function(error, element) {
// add the class of help-block
error.addClass('help-block');
// add the error element after the input element
error.insertAfter(element);
}
});
}
// -------------------------
what I am doing wrong here please help me.

Related

Modal needs to both verify fields are entered, and close upon clicking the submit button

I have a modal i'm working on that, for whatever reason, will either dismiss upon clicking submit without validating the form field inputs, or it will simply reload the form upon entering and never go away, preventing my webpage from then being seen. My idea is that this will show upon opening the webpage, the user is required to enter information into it, and then proceed to the rest of my webpage unhindered. My modal form code is as follows:
<div class="modal fade" id="formModal" tabindex="-1" role="dialog" aria-labelledby="formModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="formModalLabel">Services Contact Form</h3>
<button type="button" class="close" aria-label="close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="formAwesome">
<div class="modal-body">
<div class="form-group row">
<label for="firstName" class="col-sm-6 col-form-label">
First name
</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="firstName" placeholder="John" required>
</div>
</div>
<div class="form-group row">
<label for="lastName" class="col-sm-6 col-form-label">
Last name
</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="lastName" placeholder="Doe" required>
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-6 col-form-label">
E-mail address
</label>
<div class="col-sm-6">
<input type="email" class="form-control" id="email" placeholder="john.doe#email.com" required>
</div>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="awesomeCheck">
<label class="form-check-label" for="awesomeCheck">
Yes, I consent to contact.
</label>
</div>
</div>
<div class="modal-footer">
<!--<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> -->
<button type="submit" class="btn btn-primary" >Submit</button>
</div>
</form>
</div>
</div>
</div>
and this is my css:
<style>
#loading-img{
display:none;
}
.response_msg{
margin-top:10px;
font-size:13px;
background:#E5D669;
color:#ffffff;
width:250px;
max-width:100%;
padding:3px;
display:none;
}
</style>
finally with this being my ajax query:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#contact-form").on("submit",function(e){
e.preventDefault();
if($("#contact-form [name='your_name']").val() === '')
{
$("#contact-form [name='your_name']").css("border","1px solid red");
}
else if ($("#contact-form [name='your_email']").val() === '')
{
$("#contact-form [name='your_email']").css("border","1px solid red");
}
else
{
$("#loading-img").css("display","block");
var sendData = $( this ).serialize();
$.ajax({
type: "POST",
url: "get_response.php",
data: sendData,
success: function(data){
$("#loading-img").css("display","none");
$(".response_msg").text(data);
$(".response_msg").slideDown().fadeOut(3000);
$("#contact-form").find("input[type=text], input[type=email], textarea").val("");
}
});
}
});
$("#contact-form input").blur(function(){
var checkValue = $(this).val();
if(checkValue != '')
{
$(this).css("border","1px solid #eeeeee");
}
});
});
</style>
Again, I would like to be able to have my modal form validated upon click submit and then to close without re-opening over and over(which is currently happening). So far I have tried the following:
$('#CompanyProfile').modal('hide');
then:
<button type="button" id="close_btn" class="close" data-dismiss="modal" aria-hidden="true">
<i class = "icons-office-52"></i>
</button>
$("#close_btn").trigger("click");
then:
$('#closemodal').click(function() {
$('#modalwindow').modal('hide');
});
and these all either JUST close the modal, or do not allow for the validation process to take place. If what i'm asking is not possible. I'd like to discuss alternatives.

trouble sending modal form contents to PHP file with AJAX and Jquery

I'm trying to learn how to submit form data to a PHP file from a bootstrap modal. From the other questions I've seen, I thought I had it right, but I keep getting the error dialog. I must be missing something obvious.
test.php
<html>
<body>
<div class="container padding-top-10 change-width">
<div class="row padding-top-20" align="center">
<button class="btn btn-warning btn-lg" data-toggle="modal" data-target="#bandModal">Add Band(s)</button>
</div>
</div>
<div id="thanks"></div>
<div class="modal fade" id="bandModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content modal-lg">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="bandModalLabel">
Add a Show
</h4>
</div>
<!-- Modal Body -->
<div class="modal-body row">
<div class="container col-md-12">
<form id="addBandForm">
<h3>Band Details<small>Enter each band name and primary contact information...</small></h3>
<div class="well" id="newBandRows">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for "newBandName">Band Name:</label>
<input type="text" class="form-control" id="newBandName" name="newBandName" placeholder="Enter Band Name" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="primaryContact">Primary Contact:</label>
<input type="text" class="form-control" id="primaryContact" name="primaryContact" placeholder="Enter Name" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for "personEmail">Primary Email:</label>
<input type="email" class="form-control" id="primaryEmail" name="primaryEmail" placeholder="Enter Email" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for "personPhone">Primary Phone #:</label>
<input type="text" class="form-control" id="primaryPhone" name="primaryPhone" placeholder="Enter Phone #" />
</div>
</div>
</div>
</div>
<div id="newRowButton">
<div class="row">
<div class="col-md-1">
<button type="button" class="btn btn-success pull-left" onClick="addNewBandRow();">+</button>
</div>
<div id="remover" class="col-md-1">
</div>
<div class="col-md-7">
</div>
<div class="col-md-3 padding-top-10">
<button id="addBandSubmit" class="btn btn-primary pull-right">Submit</button>
</div>
</div>
</div>
<script src="js/newBand.js" type="text/javascript"></script>
</form>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
</body>
</html>
Jquery
$(function() {
//twitter bootstrap script
$("#addBandSubmit").click(function() {
$.ajax({
type: "POST",
url: "womhScripts/addBand.php",
data: $('#addBandForm').serialize(),
success: function(msg) {
$("#thanks").html(msg)
$("#bandModal").modal('hide');
},
error: function(xhr, status, error) { var err = eval("(" + xhr.responseText + ")"); alert(err.Message); }
});
});
});
addBand.php
<?php
if (isset($_POST['newBandName'])) {
$bandName = strip_tags($_POST['newBandName']);
$contact = strip_tags($_POST['primaryContact']);
$email = strip_tags($_POST['primaryEmail']);
$phone = strip_tags($_POST['primaryPhone']);
echo "bandName =".$bandName."</br>";
echo "contact =".$contact."</br>";
echo "email =".$email."</br>";
echo "phone =".$phone."</br>";
echo "<span class="label label-info" >your message has been submitted .. Thanks you</span>";
}?>
I looked through your code and found quite a few errors.
In your test.php change the Submit button from a button to an actual submit button.
<input id="addBandSubmit" type="submit" class="btn btn-primary pull-right">Submit</input>
In your Jquery
Add the preventDefault() function to stop the form from submitting to the same page.
$("#addBandForm").submit(function(event) {
event.preventDefault();
$.ajax({
url: "womhScripts/addBand.php",
type: "POST",
data: $('#addBandForm').serialize(),
success: function(msg) {
$("#thanks").html(msg);
$("#bandModal").modal('hide');
},
error:function(errMsg) {
console.log(errMsg);
}
});
});
You can read about what the preventDefault function here https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
In your addBand.php change the double quotes around your label label-info to single quotes. You cannot have double/single quotes inside double/single quotes inside php.
echo "<span class='label label-info' >your message has been submitted .. Thanks you</span>";
Also it helps to use the console to see exactly what is being posted using the Network tab in Chrome or Firefox .
Please mark this as the answer if it works for you. Hope this helps.

Viewing and Updating Data throught Modal Box In Laravel

guys. I need some help in viewing my data throught a modal box and replace it using update function.
Here's my button to view the modal box
{{ Form::open(array(
'route' => array('edit_spk', 'id'=> $spk_data->id),
'method' => 'put',
'style' => 'display:inline'
))
}}
<button class="btn btn-success btn-line btn-rect" data-toggle="modal" data-target="#editSpk"><i class="icon-pencil icon-white"></i> Edit</button>
{{ Form::close() }}
Here's my view code for this modal box
<div class="col-lg-12">
{{ Form::open(array('url'=>'edit_spk','class'=>'form-horizontal', 'id'=>'block-validate')) }}
<div class="modal fade" id="editSpk" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="H4"> Edit SPK</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label class="control-label col-lg-2">Distribution Code</label>
<div class="col-lg-10">
<div class="input-group">
<input class="form-control" id="distribution_code" name ="distribution_code" type="text" data-mask="M99/99/99/9999"/>
<span class="input-group-addon">M99/99/99/9999</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2">Destination</label>
<div class="col-lg-9">
<input type="text" id="destination" name="destination" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2">HLR</label>
<div class="col-lg-9">
<input type="text" id="hlr" name="hlr" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2">First ICCID</label>
<div class="col-lg-9">
<input type="text" id="first_iccid" name="first_iccid" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2">Last ICCID</label>
<div class="col-lg-9">
<input type="text" id="last_iccid" name="last_iccid" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2">Quantity</label>
<div class="col-lg-9">
<input type="text" id="quantity" name="quantity" class="form-control" />
</div>
</div>
<div class="form-actions no-margin-bottom" style="text-align:center;">
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-line btn-rect" id="confirm">Update SKU</button>
</div> </div>
{{Form::close()}}
</div>
</div>
</div>
</div>
<!--END OF MODAL EDIT SPK-->
<!-- Dialog show event handler -->
<script type="text/javascript">
$('#editSpk').on('show.bs.modal', function (e) {
$message = $(e.relatedTarget).attr('data-message');
$(this).find('.modal-body p').text($message);
$title = $(e.relatedTarget).attr('data-title');
$(this).find('.modal-title').text($title);
var form = $(e.relatedTarget).closest('form');
$(this).get('.modal-body #distribution_code').data('form', form);
$(this).get('.modal-body #destination').data('form', form);
$(this).get('.modal-body #hlr').data('form', form);
$(this).get('.modal-body #first_iccid').data('form', form);
$(this).get('.modal-body #last_iccid').data('form', form);
$(this).get('.modal-body #quantity').data('form', form);
});
<!-- Form confirm (yes/ok) handler, submits form -->
$('#editSpk').find('.modal-footer #confirm').on('click', function(){
$(this).data('form').submit();
});
</script>
Here's the route :
Route::put('spk/edit/{id}', array('as'=>'edit_spk','uses'=>'SpkController#edit'));
And here's the controller
public function edit($id)
{
$spk = Spk::find($id);
$spk->title = Input::get('distribution_code');
$spk->body = Input::get('destination');
$spk->done = Input::get('hlr');
$spk->done = Input::get('first_iccid');
$spk->done = Input::get('last_iccid');
$spk->done = Input::get('quantity');
$spk->save();
Session::flash('message', 'Successfully updated SPK !');
return Redirect::to('spk_view');
}
Can someone help me to get the data and view it into the element in modal box and make it updated using laravel ? thanks for your kindness :)
I encountered the same problem, here is how i solved it.
My modal is on the index.blade page, as follows:
<a data-toggle="modal" role="button" href="{{ URL::to('user/'.$user->id.'/edit') }}" class="btn btn-default"><i class="icon-pencil"></i></a>
Then the modal:
#if(!empty($user))
<!-- Form modal -->
<div id="edit_modal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><i class="icon-paragraph-justify2"></i> Edit User</h4>
</div>
<!-- Form inside modal -->
{!! Form::model($user,array('route' => ['user.update', $user->id],'method'=>'PATCH')) !!}
<div class="modal-body with-padding">
<div class="form-group">
<div class="row">
<div class="col-sm-12">
<label>First name</label>
<input type="text" class="form-control" placeholder="Chinedu"
name="name" value="{!! $user->name !!}">
</div>
</div>
</div>
{!! Form::close() !!}
#endif
#if(!empty($user))
<script>
$(function() {
$('#edit_modal').modal('show');
});
</script>
#endif
My controller methods are:
public function index()
{
//View all users
$users= User::orderBy('name', 'ASC')->paginate(10);
return view('user.index',compact('users'));
}
public function edit($id)
{
//
$users= User::orderBy('name', 'ASC')->paginate(10);
$user= User::findOrFail($id);
return view('user.index',compact('users','user'));
}
Hope this helps

How to set password and username in javascript for a form placed inside a bootstrap modal

I have put a login modal using bootstrap 3 as explained in the link
http://bootstrapvalidator.com/examples/modal/
In the JavaScript code how to set the username and password to a particular value for the login form.
I am still learning html and css. I don't know much about javascript.
$('input[name="username"]').val('user');
$('input[name="password"]').val('password')
http://jsfiddle.net/sp5fcaLm/
Although I'm not sure setting password directly is the best idea.
You can try:
HTML code:
<div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Login</h4>
</div>
<div class="modal-body">
<!-- The form is placed inside the body of modal -->
<form id="loginForm" method="post" class="form-horizontal">
<div class="form-group">
<label class="col-sm-3 control-label">Username</label>
<div class="col-sm-5">
<input type="text" class="form-control" name="username" id="username" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Password</label>
<div class="col-sm-5">
<input type="password" class="form-control" name="password" id="password" />
</div>
</div>
<div class="form-group">
<div class="col-sm-5 col-sm-offset-3">
<button type="submit" class="btn btn-default">Login</button>
</div>
</div>
</form>
</div>
</div>
</div>
and javascript code:
$('#loginModal').on('shown.bs.modal', function() {
$('#username').val('example#gmail.com');
$('#password').val('123456');
});
Remember include twitter-bootstrap. Its here

How to specify separate contact scripts for different buttons

I am trying to point my scripts to two different buttons in my html. The scripts both send an email of what the customer entered however both belong to two separate modal forms.
The first form is:
!-- Beginning of Pop-up Device Form -->
<div class="btn-buy hover-effect" data-toggle="modal" data-target="#modal-1"></div>
<div class="modal fade" id="modal-1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">SpryMobile Device Testing</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<form id="emailForm">
<h4>Name</h4>
<p><input name="contactName" id="contactName" class="form-control" type="text" /></p>
</div>
<div class="col-md-6">
<h4>Email Address</h4>
<p><input class="form-control" required name="contactEmail" id="contactEmail" type="email" /></p>
</div>
<div class="col-md-12">
<h4>Tell us about your operation</h4>
<input type="hidden" value="Device and Meter Testing" id="contactType"/>
<textarea rows="7" cols="20" class="form-control" name="contactMessage" id="contactMessage"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn-u btn-u-default" data-dismiss="modal">Close</button>
<input type="submit" value="Send Message" class="btn-u" id="contactSubmit" name="contactSubmit"> <i id="contactSpinner" class="icon-spinner icon-spin" style="display:none;"></i></button>
<br>
<div class="alert alert-success" id="messageSuccess" style="display:none;">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>Thank you!</strong> We appreciate your comments, and will get back to you soon.
</div>
<br>
<div class="alert alert-danger" id="messageError" style="display:none; padding-bottom:35px;">
<button class="close" data-dismiss="alert">x</button>
<div style="float:left;"><strong>Sorry.</strong> There was a problem with the server.</div>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- End of pop-up -->
The script that I have associated with this modal form is:
<script type="text/javascript">
$(document).ready(function() {
$('#emailForm').on('submit', function(event) {
event.preventDefault();
if( ! $("form")[0].checkValidity() ) {
return false;
}
// Disable the submit button
$('#contactSubmit').attr("disabled", "disabled");
$('#contactSpinner').css('display', 'inline-block');
$.ajax({
type : "POST", cache: false,
url : "#controllers.routes.Application.contactSend()",
data : {
contactName: $("#contactName").val(),
contactEmail: $("#contactEmail").val(),
contactMessage: encodeURIComponent( $("#contactMessage").val() ),
contactType: $("#contactType").val()
},
success : function(msg) {
// Check to see if the mail was successfully sent
if (msg == 'OK_SO_UPDATE') {
$("#messageSuccess").css("display", "block");
}
},
error : function(ob, errStr) {
$("#messageError").css("display", "block");
$("#messageError span.message").text(ob.responseText);
},
complete: function() {
$('#contactSubmit').removeAttr("disabled");
$('#contactSpinner').css('display', 'none');
}
});
return false;
});
});
</script>
This is referencing the scripts by giving the my form an id of "emailForm". However, if I wanted to add a second modal form such as:
<!-- Beginning of Pop-up Professional Form -->
<div class="btn-buy hover-effect" data-toggle="modal" data-target="#modal-2"></div>
<div class="modal fade" id="modal-2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">SpryMobile Professional</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<form id="emailForm">
<h4>Name</h4>
<p><input name="contactName" id="contactName" class="form-control" type="text" /></p>
</div>
<div class="col-md-6">
<h4>Email Address</h4>
<p><input class="form-control" required name="contactEmail" id="contactEmail" type="email" /></p>
</div>
<div class="col-md-12">
<h4>Tell us about your operation</h4>
<input type="hidden" value="Professional" id="contactType"/>
<textarea rows="7" cols="20" class="form-control" name="contactMessage" id="contactMessage"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn-u btn-u-default" data-dismiss="modal">Close</button>
<input type="submit" value="Send Message" class="btn-u" id="contactSubmit" name="contactSubmit"> <i id="contactSpinner" class="icon-spinner icon-spin" style="display:none;"></i></button>
<br>
<div class="alert alert-success" id="messageSuccess" style="display:none;">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>Thank you!</strong> We appreciate your comments, and will get back to you soon.
</div>
<br>
<div class="alert alert-danger" id="messageError" style="display:none; padding-bottom:35px;">
<button class="close" data-dismiss="alert">x</button>
<div style="float:left;"><strong>Sorry.</strong> There was a problem with the server.</div>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- End of pop-up -->
This references the same script since I gave this form the id of emailForm as well. However, for some reason the alerts that are suppose to appear for the second form are not showing up. Any idea what this could be? Will I need to create a unique script for each form?
Duplicate ID's violate the specifications and are problematic, but here's a way around that to temporarily repair this code.
$(event.target).find("#messageError").css("display", "block");
The FORM tag is also malformed. I moved it up to match the bottom form tag (to after the fourth DIV).
(There are many duplicate ID problems yet unresolved, but the above specifies to the program within the event listener which element to reveal.)
The solution is to use class and name attributes where appropriate.
JSFiddle: http://jsfiddle.net/BloodyKnuckles/s7D98/

Categories

Resources