I have a form with a button whose id is calbtn. The form has two input fields whose ids are input1 and input2.
I want to check if the inputs are empty after I click callbtn. If the inputs are empty, then display the alert box (whose id is failurebox) else submit the form.
But this function is executed only once during its first time. When I click again callbtn does not execute the check function. If I leave either of my input1 or input2 empty for second time.
Please help me solve this problem. I am new to using jQuery. Please correct my below jquery code.
$(document).ready(function() {
$("#calbtn").on('click', function() {
if ($("#tempsp").val() == "" || $("#temppv").val() == "")
$("#failurebox").show();
});// end of click function
});
My HTML code is
<form id="newlayerform" role="form" method="post" class="form-horizontal" >
<div class="form-group">
<label for="tempsp" class="col-sm-4 control-label" style="color:red">Temp Set Point</label>
<div class="col-sm-8">
<div class="input-group">
<input type="number" class="form-control" name="tempsp" id="tempsp" placeholder="Enter Temp Set Point">
<div class="input-group-addon"><b>deg.Celcius</b></div>
</div><!--end of input group-->
</div>
</div>
<div class="form-group">
<label for="temppv" class="col-sm-4 control-label" style="color:red">Temp Process</label>
<div class="col-sm-8">
<div class="input-group">
<input type="number" class="form-control" name="temppv" id="temppv" placeholder="Enter Temp Process">
<div class="input-group-addon"><b>deg.Celcius</b></div>
</div><!--end of input group-->
</div>
</div>
<button type="button" class="btn btn-success btn-lg btn-block" id="calbtn" name="calbtn">Calculate</button>
</form>
<div id="failurebox" class="alert alert-warning" style="display:none">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
Failure
</div>
The form should not be submitted. Use return false; to stop form from submitting.
$(document).ready(function() {
$("#calbtn").on('click', function() {
if (!$.trim($("#input1").val()) || !$.trim($("#input2").val())) {
$("#failurebox").show();
} else {
$("#failurebox").hide();
}
}); // end of click function
});
Try this: jquery way of checking if an input is empty:
$(document).ready(function() {
$("#calbtn").on('click', function() {
if (!$("#input1").val() || !$("#input2").val()) {
$("#failurebox").show();
}
}); // end of click function
});
I think I've gotten it to work using this sqlfiddle
I did it like this:
$(document).ready(function() {
$("#calbtn").click(function() {
if (!$("#tempsp").val() || !$("#temppv").val())
{
$("#failurebox").show();
}
else{
$("#failurebox").hide();
}
});// end of click function
});
EDIT: my bad I made a slight mistake but fixed it now, should work now
I have got the problem solved.
The problem was in my alert box. I have used dismissible alert box with a close button. When I get the error for first time I was just closing my alert box which is preventing from getting the alert again when I do it for the second time.
The click function was working fine but the problem was due to the alert box.
Related
I have a form that uses the jquery form validator plugin (http://www.formvalidator.net/) to perform client side pre-submit validation. I have the toggleDisabled module activated so that the submit button is disabled until all required fields are filled out and formatted correctly. My jquery then sends the form data to a processing page via ajax. The storeData.php code stores the data in a table. On success, the ajax should open a modal. I have verified that the data is being stored in my table.
The issue lies (I suspect) with the form submit button. In order for my toggleDisabled module to work correctly, the button has to be of type 'submit.' But because of the nature of a submit button the success function of my ajax is effectively being bypassed so that the modal will never be displayed.
I have tested this by changing the submit button to a regular button. At the expense of my toggleDisabled module not functioning this way, my modal is displayed.
I have found many solutions here for enabling/disabling buttons and also for preventing form submit by changing the button type to button. However, I want to use the validator module to disable/enable the button because it is designed to listen to the data-validation attributes for my form fields. But it won't work unless it's a submit button. Is there a simple solution that I'm overlooking?
index.php
<form method="post" name="talentForm" id="talentForm">
<div class="form-row">
<div class="col-auto redtext">*</div>
<div class="col">
<input type="text" id="first" class="form-control" placeholder="First name" data-validation="required">
</div>
<div class="col-auto"> </div>
<div class="col-auto redtext">*</div>
<div class="col">
<input type="text" id="last" class="form-control" placeholder="Last name" data-validation="required">
</div>
</div>
<div class="row rowtm20"></div>
<div class="form-row">
<div class="col-auto redtext">*</div>
<div class="col">
<input type="text" id="email" class="form-control" placeholder="E-mail" data-validation="email">
</div>
<div class="col-auto"> </div>
<div class="col-auto"> </div>
<div class="col">
<input type="text" id="phone" class="form-control" placeholder="Phone">
</div>
</div>
<div class="form-row">
<button type="submit" id="registerButton" class="btn btn-primary mb-2 biggertext">Register</button>
</div>
</form>
<script>
$.validate({
modules : 'security,toggleDisabled',
showErrorDialogs : false
});
$('#registerButton').on('click', function(){
var inputData = $('#last').val()+"|"+$('#fist').val()+"|"+$('#email').val()+"|"+$('#phone').val();
$.ajax({
type: 'post',
url: 'storeEntry.php',
data: {registration:inputData},
success: function(response){
if(response == "1"){
$("#thankyouModal").modal("show");
}
else{
alert("Error");
}
}
});
});
</script>
storeEntry.php
if(isset($_POST)){
$data = explode("|",$_POST['registration']);
$addRegistration = "insert into talent (Last,First,email,Phone) values('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."')";
$entry = $dbConn->query($addRegistration) or die ("Error performing addRegistration query: ".mysqli_error($dbConn));
if($entry){
echo "1";
} else{
echo "0";
}
}
Well, I found the answer. I added an argument to the click function and then called the preventDefault method, which will effectively 'turn off' the submit action of a submit button. This allows my toggleDisabled module in the validator to function correctly while also allowing my modal to appear and my ajax to execute. Hre is my revised click function:
$('#registerButton').on('click', function(e){
e.preventDefult();
var inputData = $('#last').val()+"|"+$('#fist').val()+"|"+$('#email').val()+"|"+$('#phone').val();
$.ajax({
type: 'post',
url: 'storeEntry.php',
data: {registration:inputData},
success: function(response){
if(response == "1"){
$("#thankyouModal").modal("show");
}
else{
alert("Error");
}
}
});
});
I have two elements of members data such as id and some other info in a modal which are hidden input elements inside my modal, I bind data from a anchor tag using javascript, example of data element in the anchor tag:
data-column="'.htmlspecialchars($column, ENT_QUOTES, 'utf-8').'"
Javascript example to bind into the modal:
$('#EnterExpiryModal').on('show.bs.modal', function (e) {
var memberID = $(e.relatedTarget).data('id');
$('#memID232').val(memberID);
var cola3 = $(e.relatedTarget).data('column');
$('#column3').val(cola3);
});
Having the relevant data for the members in question in my modal (modal code snippet below):
<div class="modal" id="EnterExpiryModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<div id="ExpiryError"></div>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Please enter document expiry date</h4>
<br>
<form class="form-horizontal" method="post" id="ExpiryDateForm">
<div class="form-group">
<input id ="memID232" name="memID232" class="form-control" type="hidden">
</div>
<div class="form-group">
<input id ="column3" name="column3" class="form-control" type="hidden">
</div>
<div class="form-group">
<label class="col-md-4 control-label">Date</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group">
<div class="clearfix">
<div id="date" data-placement="left" data-align="top" data-autoclose="true">
<input name="date" type="text" class="form-control hasDatepicker" placeholder="Choose Date">
</div>
</div>
</div>
</div>
</div>
<div class="middleme"><p><i class="fa fa-info-circle iwarner" aria-hidden="true"></i><small> These documents can be uploaded again at any time...</small></p></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" id="expirySubmit" name="expirySubmit" class="btn clocumsbtn">Confirm</button>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
The above code produces the below modal:
As you can see user is prompted to enter a expiry date in the form field and click confirm.
However the issue I am having is when I hit submit the form does submit, my jQuery validation does all the necessary checks before submitting using ajax, but my hidden input elements don't submit with the values as they should, they appear to be empty, but the datepicker (date) field is populated - I know the values populate with the required data I need.
Here's what the modal looks like without the elements being hidden:
Here is the validation:
$("#ExpiryDateForm").validate({
rules:
{
memID232: {
required: true,
minlength: 0
},
column3: {
required: true,
minlength: 0
},
date: {
required: true,
minlength: 3
}
},
messages:
{
memID232: "There's an error",
column3: "There's an error",
date: "Please enter the expiry date",
},
submitHandler: submitExpiryDate
});
here's the submit handler:
function submitExpiryDate() {
var data = $("#ExpiryDateForm").serialize();
$.ajax({
type : 'POST',
url : 'enterdocexpiry.php',
data : data,
beforeSend: function() {
$("#expirySubmit").html('<span class="fa fa-spinner"></span> please wait...');
},
success : function(responses) {
if(responses=="1"){
$('#ExpiryError').removeClass('animated shake');
$("#ExpiryError").fadeIn(1000, function(){
$('#ExpiryError').addClass('animated shake');
$("#ExpiryError").html('<div class="alert alert-danger"> <span class="fa fa-exclamation"></span> Sorry there was an error!</div>');
});
}
else if(responses=="updated"){
$("#ExpiryError").fadeIn(2000, function(){
$("#expirySubmit").html('<span class="fa fa-spinner"></span> updating...');
$("#ExpiryError").html("<div class='alert alert-success'><span class='fa fa-check-square-o'></span> Added Expiry Date!</div>");
setTimeout(function(){
window.location.href="manage_docs.php";
},2000);
});
}
else {
$("#ExpiryError").fadeIn(1000, function(){
$("#ExpiryError").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#expirySubmit").html('<span class="glyphicon glyphicon-log-in"></span> Some other error');
});
}
}
});
return false;
}
here the php:
require "database.php";
$memberID = $_POST['memID232'];
$column = $_POST['column3'];
$date = DateTime::createFromFormat('d/m/Y',$_POST['dates']);
$expiryDate = $date->format("Y-m-d");
$docploaded = "Yes";
if (isset($_POST['expirySubmit'])) {
if ($column == "passport") {
$statement = $conn->prepare('UPDATE memberdocs SET pexpiry=:expiryDate,puploaded=:docploaded WHERE m_id=:memberID');
$statement->bindParam(':expiryDate', $expiryDate);
$statement->bindParam(':docploaded', $docploaded);
$statement->bindParam(':memberID', $memberID);
$statement->execute();
if($statement->execute() ):
echo 'updated';
else:
echo "1";
endif;
}else if ($column == "crb") {
$statement = $conn->prepare('UPDATE memberdocs SET cvexpiry=:expiryDate WHERE m_id=:memberID');
$statement->bindParam(':expiryDate', $expiryDate);
$statement->bindParam(':memberID', $memberID);
$statement->execute();
if($statement->execute() ):
echo 'updated';
else:
echo "1";
endif;
}
}
Now I have done some troubleshooting and it seems the datepicker is the issue here. If I remove the datepicker (date) form field and replace it with a standard free text input field my form submits successfully with the memID232 input field and column3 input field populated, executing my php script, I've tried to be as clear as possible I hope the screenshots and snippets help, any advice?
I don't know what happens there. [
Here you see the Edit buttonedit(pencil) in actions when i uopdate the record modal will open.
When you click on edit(pencil) button modal will be open.
When i update the record first time its working fine and ajax runs one time. when i again update the record ajax runs twice and again update the record ajax run thrice. every time when i update the record the ajax run incremented
Here is my code:-
Html code of Button
enter code here
<button type="button" class="btn btn-info btn-edit editService"><i class="fa fa-pencil" aria-hidden="true"></i></button>// this button in foreach loop
My Modal:-
enter code here
<div class="modal fade" id="myModal-edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form id="subservicedata" role="form" method="POST" action="Javascript:;">
{{ csrf_field() }}
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="add-cat">Edit Service</h4>
</div>
<div class="modal-body">
<div class="form-group row">
<span class="col-xs-3 add-cate-model">Service</span>
<div class="col-xs-8">
<input name="name" id="sname" class="form-control txtfield m-tb-10" type="text" placeholder="Service" value="">
<input type="hidden" name="id" id="id" value="">
<input type="hidden" name="serviceid" id="service_id" value="">
<input type="hidden" name="listid" id="list_id" value="">
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary editSubService">Submit</button>
</div>
</form>
</div>
</div>
My Jquery Code:-
enter code here
$(document).on ('click','.editService',function(){
var tdid = $(this).parents().parents().attr('id');
var service = tdid.split('-');
var subserviceid = service[1];
alert(subserviceid);
$.ajax({
type : "POST",
url : "get-service",
data : { id: subserviceid },
dataType: 'json',
success:function(resp){
if($.trim(resp)){
$('#myModal-edit').modal('show');
$('#sname').val(resp.name);
$('#id').val(resp.id);
$('#service_id').val(resp.service_id);
$('#list_id').val(resp.list_id);
$(document).on('click','.editSubService',function(){
$.ajax({
type : "post",
url : "edit-sub-service",
data : $("#subservicedata").serialize(),
success:function(resp){
if($.trim(resp)){
alert(resp);
alert(subserviceid);
$('#tr-'+subserviceid+' #tdid-'+subserviceid).html(resp);
$('#myModal-edit').modal('hide');
}else{
alert("Error"); return false;
}
},
error:function(){
alert("Something Went Wrong!");
}
});
});
} else{
alert("Failed"); return false;
}
}
});
});
And My laravel 5.2 function
enter code here
public function getCategoryService(Request $request){
if($request->ajax()){
$data = $request->all();
$servicedata= DB::table("session_subservices")->where('id',$data['id'])->first();
echo json_encode($servicedata);die;
}
}
public function editCategoryService(Request $request){
if($request->ajax()){
$data = $request->all();
//echo "<pre>"; print_r($data); die;
SessionSubservice::where('id', $data['id'])->update(array('name' =>$data['name']));
echo $data['name']; die;
}
}
The problem is that you append a new event every time the button is clicked.
You need to remove the first event if you want to retain your approach.
Change this $(document).on ('click','.editSubService',function(){
to this:
$(document).off('click').on('click','.editSubService',function(){
Other aproach is to create a function in your js and set it to be called in the html.
The problem is the .editSubSerice click handler:
$(document).on('click','.editSubService',function(){
...
}
You are adding this click handler in the success function of your ajax call which is part of another click handler, so every time that ajax call / click handler executes, you add an additional click handler and that causes the code to execute multiple times.
You should move that click handler to after (or before...) your other click handler so that it only gets called / binds once.
I am creating a content management system using bootstrap, jQuery, php, mySQL.
I am wondering how I can make something work better.
Right now, I have an invoice page with buttons to 'Add Service...',
Add Accessory...', 'Add Payment...', and so on.
When the user clicks on the buttons to add anything, a bootstrap modal form shows. Ajax is used with jQuery to process the insert and then the invoice table refreshes showing the new invoice information.
If the user clicks on an item in the invoice table, I have the same bootrap modal form appear with the fields filled in the form to view. The "Save" button now says "Update." If info is changed the record is automatically updated in my database and the invoice table refreshes.
How I'm doing this:
The invoice table has a script that sees if the item is clicked. If so, it updates the 'Save' button to say 'Update'. Then when the 'Update' button is clicked, the invoice page has jQuery that runs the update script and then changes the button back to say 'Save' and resets the form.
All the item data is stored in 'data-whatever' attributes hidden on the invoice form. So when the update modal form loads, the 'data-whatever' fields are sent one-by-one to the modal form's inputs. I have it coded to send the fields to the appropriate field inputs.
It doesn't seem right to me.
Here's a modal which is included on the invoice.php page:
<!-- /.modal -->
<div class="modal fade" id="modal_form_invoice_payment" tabindex="-1" role="dialog" 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">Add/Update/View Payment...</h4>
</div>
<div class="modal-body">
<!-- BEGIN FORM-->
<form name="payment_form" id="payment_form" data-invid="<?php echo $invoice_id; ?>" method="POST" class="horizontal-form">
<div class="form-body">
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
You have some form errors. Please check below.
</div>
<div class="alert alert-success display-hide">
<button class="close" data-close="alert"></button>
Your form validation is successful!
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Type</label>
<select id="types_payments_id" name="types_payments_id" class="form-control">
<option value="">Select One...</option>
<?php
if($company->find_types_payments()) {
$types_payments = $company->types_payments();
foreach ($types_payments as $types_payment_option) {
echo '<option value="' . $types_payment_option->id . '">' . $types_payment_option->category . '</option>';
};
};
?>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Entered Date</label>
<div class="input-icon right">
<i class="fa"></i>
<input type="text" id="entered_date" name="entered_date" class="datepicker form-control" value="">
</div>
</div>
</div>
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Amount Paid</label>
<div class="input-icon right">
<i class="fa"></i>
<input type="text" id="amount_paid" name="amount_paid" class="currency_mask form-control" value="">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Note</label>
<div class="input-icon right">
<i class="fa"></i>
<input type="text" id="note" name="note" class="form-control" value="">
</div>
</div>
</div>
</div>
<!--/row-->
</div>
<input type="hidden" id="inv_payments_id" value="">
<input type="hidden" id="invoice_id" name="invoice_id" value="<?php echo $invoice_id; ?>">
<input type="hidden" id="contact_id" name="contact_id" value="<?php echo $contact->data()->id; ?>">
<input type="hidden" id="company_id" name="company_id" value="<?php echo $company->data()->id; ?>">
<div class="modal-footer form-actions right">
<button id="cancelPayment" type="button" class="btn default" data-dismiss="modal">Cancel</button>
<button id="submitPayment" type="submit" class="btn blue">Save</button>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
Here's some code from my invoice.php page:
if($invoice->find_items_refunds()) {
$db = $invoice->items_refunds();
foreach($db AS $result) {
echo '<tr>
<td class="refund" data-inv_refunds_id="' . $result->id .'">
Refund
<br/><br/>
<div class="items_buttons" style="display:none">
<button type="button" data-deleteID="' . $result->id . '" data-table="invoice_refunds" class="edit_refund edit_button btn btn-xs default">
<i class="fa fa-pencil"></i>
</button>
<button type="button" data-deleteID="' . $result->id . '" data-table="invoice_refunds" class="delete_button btn btn-xs default">
<i class="icon-trash"></i>
</button>
</div>
</td>
<td>' . $result->description . '</td>
<td id="refund_entered_date">' . $result->entered_date . '</td>
<td>1</td>
<td>
</td>
<td id="refund_amount_refunded">
$' . $result->amount_refunded . '
</td>
<td></td>
<td id="types_payments_id" style="display:none">' . $result->types_payments_id . '</td>
<td id="refund_note" style="display:none">' . $result->refund_note . '</td>
</tr>';
}
}
This is a sample from the invoice that shows 'payments.' I am hiding information in the payments rows like it's id for instance. Then when that row is clicked on the invoice page I have separate jQuery that opens the same form I use to 'save' new payment info, but this time it populates the form with the data (hidden and visible) from the payment row.
Is there a better way? If I have a table record that has a lot of data in it, I don't think I'd want to hide all of that info in the row.
I'm thinking what I need to do is find a way that when the modal form opens, and if I'm updating a record then query the database for ALL the information to fill the fields in the form.
I hope I explained that right.
Or do should I just make an "Add form" and a separate "Update form"? I thought it would be better practice to have one form and use it to add new data and update it whenever it's shown.
Here's the javascript that handles the form:
//when cancel is selected while on bootsrap modal forms, reset whole form. must do for each modal
$("#modal_form_invoice_payment #cancelPayment").click(function() {
//reset form, hide it, and reload table and totals
$('#modal_form_invoice_payment').find('form')[0].reset();
//remove checkmark from any field that was validation successfully and remove green outline from has-success validation
$('#modal_form_invoice_payment .fa').removeClass('fa-check');
$('#modal_form_invoice_payment .form-group').removeClass('has-success');
$('#modal_form_invoice_payment .form-group').removeClass('has-error');
$('#modal_form_invoice_payment .fa').removeClass('fa-warning');
$('#modal_form_invoice_payment .alert').hide();
$('#modal_form_invoice_payment #submitPayment').html('Save');
});
$('.edit_payment').click(function() {
//once edit_payment is clicked, disable all edit feature and restore invoice table back to normal.
$('#invoice_block .edit_me').editable('toggleDisabled');
//show/hide buttons for items
if($('.items_buttons').is(":visible")) {
$('.items_buttons').hide();
} else {
$('.items_buttons').show();
}
if($("#print").is(":visible")) {
$('#print').hide();
} else {
$('#print').show();
}
//enable/disable add and delete buttons accordingly.
if($('#add_button').is(":disabled")) {
$('#add_button').attr("disabled",false);
} else {
$('#add_button').attr("disabled",true);
}
if($('#delete_button').is(":disabled")) {
$('#delete_button').attr("disabled",false);
} else {
$('#delete_button').attr("disabled",true);
}
//make the text value of id's parsed into integers so the dropdown can be populated with that value. has to be changed to int fist, else doesn't populate.
//also trim description - remove white spaces from how this table is formatted.
var $payments_id = $(this).closest("tr").find(".payment").attr("data-inv_payments_id");
var $types_payments_id = parseInt($(this).closest("tr").find("#types_payments_id").text() , 10);
var $payment_note = $.trim($(this).closest("tr").find("#payment_note").text());
var $payment_amount_paid = $(this).closest("tr").find("#payment_amount_paid").text();
var $payment_entered_date = $(this).closest("tr").find("#payment_entered_date").text();
//set update form values and changed text from Save to Update
$('#modal_form_invoice_payment #inv_payments_id').val($payments_id);
$('#modal_form_invoice_payment #types_payments_id').val($types_payments_id);
$('#modal_form_invoice_payment #note').val($payment_note);
$('#modal_form_invoice_payment #amount_paid').val($payment_amount_paid);
$('#modal_form_invoice_payment #entered_date').val($payment_entered_date);
$('#modal_form_invoice_payment #submitPayment').html('Update');
$('#modal_form_invoice_payment').modal('show');
});
Here's the jQuery that handles the form validation:
//VALIDATE PAYMENT FORM
var form_payment = $('#payment_form');
var inv_id_payment = $('#payment_form').attr("data-invid");
var error_payment = $('.alert-danger', form_payment);
var success_payment = $('.alert-success', form_payment);
var validateAdjustment = $('#payment_form').validate({
errorElement: 'span', //default input error message container
errorClass: 'help-block help-block-error', // default input error message class
focusInvalid: true, // do not focus the last invalid input
ignore: "", // validate all fields including form hidden input
rules: {
entered_date: {
required: true
},
amount_paid: {
required: true
},
types_payments_id: {
required: true
}
},
invalidHandler: function (event, validator) { //display error alert on form submit
success_payment.hide();
error_payment.show();
App.scrollTo(error_payment, -200);
},
errorPlacement: function (error, element) { // render error placement for each input type
var icon = $(element).parent('.input-icon').children('i');
icon.removeClass('fa-check').addClass("fa-warning");
icon.attr("data-original-title", error.text()).tooltip();
},
highlight: function (element) { // hightlight error inputs
$(element)
.closest('.form-group').removeClass("has-success").addClass('has-error'); // set error class to the control group
},
unhighlight: function (element) { // revert the change done by highlight
},
success: function (label, element) {
var icon = $(element).parent('.input-icon').children('i');
$(element).closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
icon.removeClass("fa-warning").addClass("fa-check");
},
submitHandler: function(form_payment) {
//remove blank inputs so they aren't passed into the db and are inserted as NULL
var data = $("#payment_form").serialize();
if($('#payment_form #submitPayment').text() == 'Save') {
//save
$.ajax({
url: "ajax_insert.php?table=invoice_payments",
type: form_payment.method,
dataType: 'json',
data: data,
success: function(response) {
//response here if data response
if (response) {
if(response.success) {
//reset form, hide it, and reload table and totals
$('#modal_form_invoice_payment').find('form')[0].reset();
error_payment.hide(); //if it's visible, hide it.
//remove checkmark from any field that was validation successfully and remove green outline from has-success validation
$('#modal_form_invoice_payment .fa').removeClass('fa-check');
$('#modal_form_invoice_payment .form-group').removeClass('has-success');
$('#modal_form_invoice_payment').modal('hide');
$('#invoice_table').load('content_invoice_table.php', { "inv_id": inv_id_payment});
$('#invoice_totals').load('content_invoice_totals.php', { "inv_id": inv_id_payment});
toastr.info('Payment entry recorded!');
} else {
toastr.error('Error!');
}
}
}
});
} else {
//get update id value from hidden field
var inv_payments_id = $('#payment_form #inv_payments_id').val();
//update
$.ajax({
url: 'ajax_update.php?table=invoice_payments&id='+inv_payments_id,
type: form_payment.method,
dataType: 'json',
data: data,
success: function(response) {
//response here if data response
if (response) {
if(response.success) {
//reset form, hide it, and reload table and totals
$('#modal_form_invoice_payment').find('form')[0].reset();
error_payment.hide(); //if it's visible, hide it.
//remove checkmark from any field that was validation successfully and remove green outline from has-success validation
$('#modal_form_invoice_payment .fa').removeClass('fa-check');
$('#modal_form_invoice_payment .form-group').removeClass('has-success');
//restore form to Save mode
$('#modal_form_invoice_payment #submitPayment').html('Save');
$('#modal_form_invoice_payment').modal('hide');
$('#invoice_table').load('content_invoice_table.php', { "inv_id": inv_id_payment});
$('#invoice_totals').load('content_invoice_totals.php', { "inv_id": inv_id_payment});
toastr.info('Payment entry updated!');
} else {
toastr.error('Error!');
}
}
}
});
};
}
});
So As Title says i have modal box which loads after the page load means it is loading after the Ajax Call and i want to validate the fields of this modal box.
for that i'm using the below code , as my HTML is not loaded in DOM :
$(document).on('click', ".add_style", function(e) {
var style_name = "";
style_name = $(".style_name").val();
if($.trim(style_name).length == 0)
{
$("#style_id").parent('div').addClass('has-error');
$(".title_error_msg").css("display","block");
return false;
}
else
{
console.log("In else");
return false;
}
});
But I'm not able to get the values of field of modal form.
Please help, Thanks n advance.
Updated :
Here is the part of the HTML
<div class="form-group">
<input type="hidden" value="" id="style_id" name="style_id">
<label>Title</label>
<input type="text" id="style_name" name="style_name" placeholder="Style Name" class="form-control style_name"> <div style="display:none" id="Styles_style_name_em_" class="errorMessage"></div> <label style="display:none;" class="control-label title_error_msg" for="inputError"><i class="fa fa-times-circle-o"></i> Please enter Style Name</label>
</div>