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?
Related
I'm new to ajax and hoping someone can help figure out how to add two form inputs. I have a hidden input that is getting the total sheets from a database. I also have an addSheets input that is getting the total of sheets to add. I'm posting code from my modal as well as the ajax and action. Any advice is greatly appreciated.
(index)
<html>
<body>
<div class="modal fade" id="addSheetsModal">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add Paper</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body px-4">
<form action="" method="post" id="form-addSheets-data">
<input type="hidden" name="id" id="id">
<input type="hidden" name="sheets" id="sheets">
<div class="form-group">
<input type="text" name="addSheets" class="form-control" id="addSheets" placeholder="">
</div>
<div class="form-group">
<input type="submit" name="addSheetQty" id="addSheetQty" value="Add Paper" class="btn btn-success btn-block">
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<script language="javascript" type="text/javascript">
// AJAX Edit Paper - Receive (Gets ID)
$("body").on("click", ".receiveBtn", function(e){
e.preventDefault();
r_edit_id = $(this).attr('id');
$.ajax({
url:"action.php",
type:"POST",
data:{r_edit_id:r_edit_id},
success:function(response){
data = JSON.parse(response);
console.log(data);
$("#id").val(data.id);
$("#sheets").val(data.sheets);
}
});
});
// Edit Paper - Update (Sums)
$("#addSheetQty").click(function(e){
if($("#form-addSheets-data")[0].checkValidity()){
e.preventDefault();
$.ajax({
url:"action.php",
type:"POST",
data: $("#form-addSheets-data").serialize()+"&action=addSheetQty",
success:function(response){
console.log(response);
Swal.fire({
title: 'Sheets added successfully!',
icon: 'success',
showConfirmButton: false,
timer: 1500
})
$("#addSheetsModal").modal('hide');
$("#form-addSheets-data")[0].reset();
showAllPapers();
}
});
}
});
</script>
<?php
// ACTION
if(isset($_POST['r_edit_id'])){
$id = $_POST['r_edit_id'];
$row = $db->getPaperById($id);
echo json_encode($row);
}
if(isset($_POST['action']) && $_POST['action'] == "addSheetQty"){
$id = $_POST['id'];
$sheets = $_POST['sheets'] + $_POST['addSheets'];
$db->updateSheetQty($id,$sheets);
}
?>
In the database the sheets column is varchar(255). In the php_error.log I'm getting this response: PHP Warning: A non-numeric value encountered in /Applications/MAMP/htdocs/PaperInventory/action.php on line 116 which is this line ($sheets = $_POST['sheets'] + $_POST['addSheets'];) in my code above.
Thanks for any input and help understanding this.
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'm trying something very simple yet can't make it work and I have no idea why. I'm trying to load details on bootstrap modal windows from database so I can edit them. My button looks like
<button onclick="GetUserDetails('.$row['row_id'].')" class="btn btn-warning">Update</button>
Then this is the php part which should load the data
include("../../misc/database.inc.php");
error_reporting(E_ALL);
ini_set('display_errors', 1);
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['row_id']) && isset($_POST['row_id']) != "") {
$row_id = $_POST['row_id'];
$value = $pdo->prepare('SELECT row_id, row_content, row_email FROM excel_table WHERE row_id = ?');
$value->bindParam(1, $id, PDO::PARAM_INT);
$value->execute();
$response = array();
if($value->rowCount() > 0){
while ($rs = $value->fetch(PDO::FETCH_ASSOC)) {
$response = $row;
}
}
else
{
$response['status'] = 200;
$response['message'] = "Data not found!";
}
echo json_encode($response);
//var_dump($_POST['row_id']); // return correct id
}
On the console->Network I see correct response
{"row_id":"1","row_content":"asd","row_email":"sad"}
Here is js part which should load data
function GetUserDetails(row_id) {
$("#row_id").val(row_id);
$.post("ajax/readUserDetails.php", {
row_id: row_id
},
function (data, status) {
// PARSE json data
var excel_table = JSON.parse(data);
// Assing existing values to the modal popup fields
$("#row_content").val(excel_table.row_content);
$("#row_email").val(excel_table.row_email);
}
);
// Open modal popup
$("#update_user_modal").modal("show");
}
And this is my modal
<div class="modal fade" id="update_user_modal" 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">Update</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="row_content">Desc</label>
<input type="text" id="row_content" placeholder="Описание" class="form-control"/>
</div>
<div class="form-group">
<label for="row_email">Email</label>
<input type="text" id="row_email" placeholder="Email" class="form-control"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="UpdateUserDetails()" >Save Changes</button>
<input type="hidden" id="row_id">
</div>
</div>
</div>
</div>
Can anyone tell me why modal isn't populated with data?
well my guess is you need to show the modal after the ajax asynchronous call end.
function GetUserDetails(row_id) {
$("#row_id").val(row_id);
$.post("ajax/readUserDetails.php", {
row_id: row_id
},
function (data, status) {
// PARSE json data
var excel_table = JSON.parse(data);
// Assing existing values to the modal popup fields
//add console.log to make sure you have some value
console.log('row_content: ' + excel_table.row_content);
$("#row_content").val(excel_table.row_content);
$("#row_email").val(excel_table.row_email);
// then add another to make sure you update it correctly.
console.log('#row_content: ' + $("#row_content").val());
// Open modal popup AFTER YOU UPDATE
$("#update_user_modal").modal("show");
}
);
}
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!');
}
}
}
});
};
}
});
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.